Introduction

This assignment is based off of this 2D object detection tutorial which uses pytorch to implement the SSD network in order to detect objects in images within the VOC Dataset. https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Object-Detection

Download dataset and create json files

Only the mount portion has to be run if you already have the dataset downloaded and the json files.

First we mount our google drive

In [1]:
from google.colab import drive
drive.mount('/content/gdrive')

# Go to the your assignment directory
%cd /content/gdrive/MyDrive/'Colab Notebooks'/ece495_assignment4/
Drive already mounted at /content/gdrive; to attempt to forcibly remount, call drive.mount("/content/gdrive", force_remount=True).
/content/gdrive/MyDrive/Colab Notebooks/ece495_assignment4

Next download the VOC 2007 Dataset. This takes 6.2 minutes.

In [2]:
import requests
import tarfile
import io
import time

def download_and_unzip(url, path):
  dl_start = time.time()
  r = requests.get(url)
  dl_end = time.time()
  print("download time elapsed:", dl_end - dl_start)
  tar = tarfile.TarFile(fileobj=io.BytesIO(r.content))
  # extract the contents of VOC2007
  extract_start = time.time()
  subdir_and_files = [
    tarinfo for tarinfo in tar.getmembers()
    if tarinfo.name.startswith("VOCdevkit/VOC2007/")
  ]
  tar.extractall(path=path, members=subdir_and_files)
  extract_end = time.time()
  print("extract time elapsed:", extract_end - extract_start)

# Go to the your assignment directory
%cd /content/gdrive/MyDrive/'Colab Notebooks'/ece495_assignment4/

start = time.time()
download_and_unzip(
    "http://host.robots.ox.ac.uk/pascal/VOC/voc2007/VOCtrainval_06-Nov-2007.tar",
    "/content/gdrive/MyDrive/Colab Notebooks/ece495_assignment4"
)
download_and_unzip(
    "http://host.robots.ox.ac.uk/pascal/VOC/voc2007/VOCtest_06-Nov-2007.tar",
    "/content/gdrive/MyDrive/Colab Notebooks/ece495_assignment4"
)
end = time.time()
print("total time elapsed:", end - start)
/content/gdrive/MyDrive/Colab Notebooks/ece495_assignment4
download time elapsed: 37.71984267234802
extract time elapsed: 115.69201183319092
download time elapsed: 34.06785225868225
extract time elapsed: 126.69275903701782
total time elapsed: 314.20646119117737

Sync the data to your google drive. This should take 33 minutes. You must restart the runtime after this by clicking Runtime -> Restart runtime.

In [3]:
start = time.time()
drive.flush_and_unmount()
end = time.time()
print("total time elapsed:", end - start)
total time elapsed: 1869.9064326286316

Check that the data is downloaded and that you have the json files. This also remounts the google drive.

In [2]:
from google.colab import drive
drive.mount('/content/gdrive', force_remount=True)

# Go to the your assignment directory
%cd /content/gdrive/MyDrive/'Colab Notebooks'/ece495_assignment4/

# Check location
!ls
## You should have this output:
# /content/gdrive/MyDrive/Colab Notebooks/ece495_assignment4
# ece495_assignment4.ipynb  utils.py  VOCdevkit
# You should also have the json files
# and also the checkpoint if you have already trained the model
Mounted at /content/gdrive
/content/gdrive/MyDrive/Colab Notebooks/ece495_assignment4
 checkpoint_ssd300_ResNet.pth.tar	   __pycache__
 checkpoint_ssd300_VGG.pth.tar		   TEST_images.json
 checkpoint_ssd300_VGG_scheduler.pth.tar   TEST_objects.json
'ece495_assignment4-2 (1).ipynb'	   TRAIN_images.json
 ece495_assignment4-2.ipynb		   TRAIN_objects.json
 label_map.json				   utils.py
 old_data				   VOCdevkit

This code does not have to be run, the files it creates are given with the assignment. It creates the json files: label_map.json, TRAIN_images.json, TRAIN_objects TEST_images.json and TEST_objects. These are the image paths, ground truth object information and label to number mapping. This should take about 45 miniutes if the data has not been cached.

In [7]:
from utils import create_data_lists
import time

start = time.time()
create_data_lists(voc07_path='/content/gdrive/MyDrive/Colab Notebooks/ece495_assignment4/VOCdevkit/VOC2007',
                  voc12_path=None, # Removed VOC 2012 to reduce data size requirement of this assignment
                  output_folder='./')
end = time.time()
print("time elapsed:", end - start)
There are 5011 training images containing a total of 15033 objects. Files have been saved to /content/gdrive/MyDrive/Colab Notebooks/ece495_assignment4.

There are 4952 test images containing a total of 14856 objects. Files have been saved to /content/gdrive/MyDrive/Colab Notebooks/ece495_assignment4.
time elapsed: 2016.6477098464966

Create the VOC Dataset loader

Next the Dataset loader for VOC is implemented

In [8]:
import torch
from torch.utils.data import Dataset
import json
import os
from PIL import Image
from utils import transform


class PascalVOCDataset(Dataset):
    """
    A PyTorch Dataset class to be used in a PyTorch DataLoader to create batches.
    """

    def __init__(self, data_folder, split, keep_difficult=False):
        """
        :param data_folder: folder where data files are stored
        :param split: split, one of 'TRAIN' or 'TEST'
        :param keep_difficult: keep or discard objects that are considered difficult to detect?
        """
        self.split = split.upper()

        assert self.split in {'TRAIN', 'TEST'}

        self.data_folder = data_folder
        self.keep_difficult = keep_difficult

        # Read data files
        with open(os.path.join(data_folder, self.split + '_images.json'), 'r') as j:
            self.images = json.load(j)
        with open(os.path.join(data_folder, self.split + '_objects.json'), 'r') as j:
            self.objects = json.load(j)

        assert len(self.images) == len(self.objects)

    def __getitem__(self, i):
        # Read image
        image = Image.open(self.images[i], mode='r')
        image = image.convert('RGB')

        # Read objects in this image (bounding boxes, labels, difficulties)
        objects = self.objects[i]
        boxes = torch.FloatTensor(objects['boxes'])  # (n_objects, 4)
        labels = torch.LongTensor(objects['labels'])  # (n_objects)
        difficulties = torch.ByteTensor(objects['difficulties'])  # (n_objects)

        # Discard difficult objects, if desired
        if not self.keep_difficult:
            boxes = boxes[1 - difficulties]
            labels = labels[1 - difficulties]
            difficulties = difficulties[1 - difficulties]

        # Apply transformations
        image, boxes, labels, difficulties = transform(image, boxes, labels, difficulties, split=self.split)

        return image, boxes, labels, difficulties

    def __len__(self):
        return len(self.images)

    def collate_fn(self, batch):
        """
        Since each image may have a different number of objects, we need a collate function (to be passed to the DataLoader).

        This describes how to combine these tensors of different sizes. We use lists.

        Note: this need not be defined in this Class, can be standalone.

        :param batch: an iterable of N sets from __getitem__()
        :return: a tensor of images, lists of varying-size tensors of bounding boxes, labels, and difficulties
        """

        images = list()
        boxes = list()
        labels = list()
        difficulties = list()

        for b in batch:
            images.append(b[0])
            boxes.append(b[1])
            labels.append(b[2])
            difficulties.append(b[3])

        images = torch.stack(images, dim=0)

        return images, boxes, labels, difficulties  # tensor (N, 3, 300, 300), 3 lists of N tensors each

Model Implementation

Base layers

First we create the base or encoder part of the network.

You must fill in the ResNet code.

In [9]:
from torch import nn
from utils import *
import torch.nn.functional as F
from math import sqrt
from itertools import product as product
import torchvision

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

class VGGBase(nn.Module):
    """
    VGG base convolutions to produce lower-level feature maps.
    """

    def __init__(self):
        super(VGGBase, self).__init__()

        # Standard convolutional layers in VGG16
        self.conv1_1 = nn.Conv2d(3, 64, kernel_size=3, padding=1)  # stride = 1, by default
        self.conv1_2 = nn.Conv2d(64, 64, kernel_size=3, padding=1)
        self.pool1 = nn.MaxPool2d(kernel_size=2, stride=2)

        self.conv2_1 = nn.Conv2d(64, 128, kernel_size=3, padding=1)
        self.conv2_2 = nn.Conv2d(128, 128, kernel_size=3, padding=1)
        self.pool2 = nn.MaxPool2d(kernel_size=2, stride=2)

        self.conv3_1 = nn.Conv2d(128, 256, kernel_size=3, padding=1)
        self.conv3_2 = nn.Conv2d(256, 256, kernel_size=3, padding=1)
        self.conv3_3 = nn.Conv2d(256, 256, kernel_size=3, padding=1)
        self.pool3 = nn.MaxPool2d(kernel_size=2, stride=2, ceil_mode=True)  # ceiling (not floor) here for even dims

        self.conv4_1 = nn.Conv2d(256, 512, kernel_size=3, padding=1)
        self.conv4_2 = nn.Conv2d(512, 512, kernel_size=3, padding=1)
        self.conv4_3 = nn.Conv2d(512, 512, kernel_size=3, padding=1)
        self.pool4 = nn.MaxPool2d(kernel_size=2, stride=2)

        self.conv5_1 = nn.Conv2d(512, 512, kernel_size=3, padding=1)
        self.conv5_2 = nn.Conv2d(512, 512, kernel_size=3, padding=1)
        self.conv5_3 = nn.Conv2d(512, 512, kernel_size=3, padding=1)
        self.pool5 = nn.MaxPool2d(kernel_size=3, stride=1, padding=1)  # retains size because stride is 1 (and padding)

        # Replacements for FC6 and FC7 in VGG16
        self.conv6 = nn.Conv2d(512, 1024, kernel_size=3, padding=6, dilation=6)  # atrous convolution

        self.conv7 = nn.Conv2d(1024, 1024, kernel_size=1)

        # Load pretrained layers
        self.load_pretrained_layers()

    def forward(self, image):
        """
        Forward propagation.

        :param image: images, a tensor of dimensions (N, 3, 300, 300)
        :return: lower-level feature maps conv4_3 and conv7
        """
        out = F.relu(self.conv1_1(image))  # (N, 64, 300, 300)
        out = F.relu(self.conv1_2(out))  # (N, 64, 300, 300)
        out = self.pool1(out)  # (N, 64, 150, 150)

        out = F.relu(self.conv2_1(out))  # (N, 128, 150, 150)
        out = F.relu(self.conv2_2(out))  # (N, 128, 150, 150)
        out = self.pool2(out)  # (N, 128, 75, 75)

        out = F.relu(self.conv3_1(out))  # (N, 256, 75, 75)
        out = F.relu(self.conv3_2(out))  # (N, 256, 75, 75)
        out = F.relu(self.conv3_3(out))  # (N, 256, 75, 75)
        out = self.pool3(out)  # (N, 256, 38, 38), it would have been 37 if not for ceil_mode = True

        out = F.relu(self.conv4_1(out))  # (N, 512, 38, 38)
        out = F.relu(self.conv4_2(out))  # (N, 512, 38, 38)
        out = F.relu(self.conv4_3(out))  # (N, 512, 38, 38)
        conv4_3_feats = out  # (N, 512, 38, 38)
        out = self.pool4(out)  # (N, 512, 19, 19)

        out = F.relu(self.conv5_1(out))  # (N, 512, 19, 19)
        out = F.relu(self.conv5_2(out))  # (N, 512, 19, 19)
        out = F.relu(self.conv5_3(out))  # (N, 512, 19, 19)
        out = self.pool5(out)  # (N, 512, 19, 19), pool5 does not reduce dimensions

        out = F.relu(self.conv6(out))  # (N, 1024, 19, 19)

        conv7_feats = F.relu(self.conv7(out))  # (N, 1024, 19, 19)

        # Lower-level feature maps
        return conv4_3_feats, conv7_feats

    def load_pretrained_layers(self):
        """
        As in the paper, we use a VGG-16 pretrained on the ImageNet task as the base network.
        There's one available in PyTorch, see https://pytorch.org/docs/stable/torchvision/models.html#torchvision.models.vgg16
        We copy these parameters into our network. It's straightforward for conv1 to conv5.
        However, the original VGG-16 does not contain the conv6 and con7 layers.
        Therefore, we convert fc6 and fc7 into convolutional layers, and subsample by decimation. See 'decimate' in utils.py.
        """
        # Current state of base
        state_dict = self.state_dict()
        param_names = list(state_dict.keys())

        # Pretrained VGG base
        pretrained_state_dict = torchvision.models.vgg16(pretrained=True).state_dict()
        pretrained_param_names = list(pretrained_state_dict.keys())

        # Transfer conv. parameters from pretrained model to current model
        for i, param in enumerate(param_names[:-4]):  # excluding conv6 and conv7 parameters
            state_dict[param] = pretrained_state_dict[pretrained_param_names[i]]

        # Convert fc6, fc7 to convolutional layers, and subsample (by decimation) to sizes of conv6 and conv7
        # fc6
        conv_fc6_weight = pretrained_state_dict['classifier.0.weight'].view(4096, 512, 7, 7)  # (4096, 512, 7, 7)
        conv_fc6_bias = pretrained_state_dict['classifier.0.bias']  # (4096)
        state_dict['conv6.weight'] = decimate(conv_fc6_weight, m=[4, None, 3, 3])  # (1024, 512, 3, 3)
        state_dict['conv6.bias'] = decimate(conv_fc6_bias, m=[4])  # (1024)
        # fc7
        conv_fc7_weight = pretrained_state_dict['classifier.3.weight'].view(4096, 4096, 1, 1)  # (4096, 4096, 1, 1)
        conv_fc7_bias = pretrained_state_dict['classifier.3.bias']  # (4096)
        state_dict['conv7.weight'] = decimate(conv_fc7_weight, m=[4, 4, None, None])  # (1024, 1024, 1, 1)
        state_dict['conv7.bias'] = decimate(conv_fc7_bias, m=[4])  # (1024)

        # Note: an FC layer of size (K) operating on a flattened version (C*H*W) of a 2D image of size (C, H, W)...
        # ...is equivalent to a convolutional layer with kernel size (H, W), input channels C, output channels K...
        # ...operating on the 2D image of size (C, H, W) without padding

        self.load_state_dict(state_dict)

        print("\nLoaded base model.\n")

class ResNetBase(nn.Module):
    """
    ResNet base convolutions to produce lower-level feature maps.
    """

    def __init__(self):
        super(ResNetBase, self).__init__()

        # TODO: Load pretrained resnet model
        self.resnet = torchvision.models.resnet50(pretrained=True)

    def forward(self, image):
        """
        Forward propagation.

        :param image: images, a tensor of dimensions (N, 3, 300, 300)
        :return: lower-level feature maps
        """
        # TODO: Add your code
        x = self.resnet.conv1(image)
        x = self.resnet.bn1(x)
        x = self.resnet.relu(x)
        x = self.resnet.maxpool(x)

        # layer conv2
        x = self.resnet.layer1(x)

        # layer conv3 -> 512
        x = self.resnet.layer2(x)
        conv_512_feats = x

        # layer conv4 -> 1024
        x = self.resnet.layer3(x)
        conv_1024_feats = x

        # Lower-level feature maps
        return conv_512_feats, conv_1024_feats

Auxiliary layers

The base layers created the low level feature maps with 512 and 1024 features. Now the higher level feature maps are created for 512, 256, 256 and 256 feature maps.

In [10]:
class AuxiliaryConvolutions(nn.Module):
    """
    Additional convolutions to produce higher-level feature maps.
    """

    def __init__(self):
        super(AuxiliaryConvolutions, self).__init__()

        # Auxiliary/additional convolutions on top of the VGG base
        self.conv8_1 = nn.Conv2d(1024, 256, kernel_size=1, padding=0)  # stride = 1, by default
        self.conv8_2 = nn.Conv2d(256, 512, kernel_size=3, stride=2, padding=1)  # dim. reduction because stride > 1

        self.conv9_1 = nn.Conv2d(512, 128, kernel_size=1, padding=0)
        self.conv9_2 = nn.Conv2d(128, 256, kernel_size=3, stride=2, padding=1)  # dim. reduction because stride > 1

        self.conv10_1 = nn.Conv2d(256, 128, kernel_size=1, padding=0)
        self.conv10_2 = nn.Conv2d(128, 256, kernel_size=3, padding=0)  # dim. reduction because padding = 0

        self.conv11_1 = nn.Conv2d(256, 128, kernel_size=1, padding=0)
        self.conv11_2 = nn.Conv2d(128, 256, kernel_size=3, padding=0)  # dim. reduction because padding = 0

        # Initialize convolutions' parameters
        self.init_conv2d()

    def init_conv2d(self):
        """
        Initialize convolution parameters.
        """
        for c in self.children():
            if isinstance(c, nn.Conv2d):
                nn.init.xavier_uniform_(c.weight)
                nn.init.constant_(c.bias, 0.)

    def forward(self, conv7_feats):
        """
        Forward propagation.

        :param conv7_feats: lower-level conv7 feature map, a tensor of dimensions (N, 1024, 19, 19)
        :return: higher-level feature maps conv8_2, conv9_2, conv10_2, and conv11_2
        """
        out = F.relu(self.conv8_1(conv7_feats))  # (N, 256, 19, 19)
        out = F.relu(self.conv8_2(out))  # (N, 512, 10, 10)
        conv8_2_feats = out  # (N, 512, 10, 10)

        out = F.relu(self.conv9_1(out))  # (N, 128, 10, 10)
        out = F.relu(self.conv9_2(out))  # (N, 256, 5, 5)
        conv9_2_feats = out  # (N, 256, 5, 5)

        out = F.relu(self.conv10_1(out))  # (N, 128, 5, 5)
        out = F.relu(self.conv10_2(out))  # (N, 256, 3, 3)
        conv10_2_feats = out  # (N, 256, 3, 3)

        out = F.relu(self.conv11_1(out))  # (N, 128, 3, 3)
        conv11_2_feats = F.relu(self.conv11_2(out))  # (N, 256, 1, 1)

        # Higher-level feature maps
        return conv8_2_feats, conv9_2_feats, conv10_2_feats, conv11_2_feats

Prediction layers

At this point we have our 6 feature maps.

The low level feature maps: (N, 512, 38, 38), (N, 1024, 19, 19)

Also the high level feature maps: (N, 512, 10, 10), (N, 256, 5, 5), (N, 256, 3, 3), (N, 256, 1, 1)

Each prior box requires a classification output of size number of classes and also the 4 box location values that are regressed. These convolutions are created in the init function.

In the forward pass all the convolutions are performed on their respective input feature maps. After that there is some work done to modify the tensors and then concatonate them in order to have the classification output shaped like (N, 8732, n_classes) and the box output to be (N, 8732, 4). This is a format that will be easier to work with when the network output is passed to the loss function during training or the output is passed through NMS during testing.

In [11]:
class PredictionConvolutions(nn.Module):
    """
    Convolutions to predict class scores and bounding boxes using lower and higher-level feature maps.

    The bounding boxes (locations) are predicted as encoded offsets w.r.t each of the 8732 prior (default) boxes.
    See 'cxcy_to_gcxgcy' in utils.py for the encoding definition.

    The class scores represent the scores of each object class in each of the 8732 bounding boxes located.
    A high score for 'background' = no object.
    """

    def __init__(self, n_classes):
        """
        :param n_classes: number of different types of objects
        """
        super(PredictionConvolutions, self).__init__()

        self.n_classes = n_classes

        # Number of prior-boxes we are considering per position in each feature map
        n_boxes = {'conv4_3': 4,
                   'conv7': 6,
                   'conv8_2': 6,
                   'conv9_2': 6,
                   'conv10_2': 4,
                   'conv11_2': 4}
        # 4 prior-boxes implies we use 4 different aspect ratios, etc.

        # Localization prediction convolutions (predict offsets w.r.t prior-boxes)
        self.loc_conv4_3 = nn.Conv2d(512, n_boxes['conv4_3'] * 4, kernel_size=3, padding=1)
        self.loc_conv7 = nn.Conv2d(1024, n_boxes['conv7'] * 4, kernel_size=3, padding=1)
        self.loc_conv8_2 = nn.Conv2d(512, n_boxes['conv8_2'] * 4, kernel_size=3, padding=1)
        self.loc_conv9_2 = nn.Conv2d(256, n_boxes['conv9_2'] * 4, kernel_size=3, padding=1)
        self.loc_conv10_2 = nn.Conv2d(256, n_boxes['conv10_2'] * 4, kernel_size=3, padding=1)
        self.loc_conv11_2 = nn.Conv2d(256, n_boxes['conv11_2'] * 4, kernel_size=3, padding=1)

        # Class prediction convolutions (predict classes in localization boxes)
        self.cl_conv4_3 = nn.Conv2d(512, n_boxes['conv4_3'] * n_classes, kernel_size=3, padding=1)
        self.cl_conv7 = nn.Conv2d(1024, n_boxes['conv7'] * n_classes, kernel_size=3, padding=1)
        self.cl_conv8_2 = nn.Conv2d(512, n_boxes['conv8_2'] * n_classes, kernel_size=3, padding=1)
        self.cl_conv9_2 = nn.Conv2d(256, n_boxes['conv9_2'] * n_classes, kernel_size=3, padding=1)
        self.cl_conv10_2 = nn.Conv2d(256, n_boxes['conv10_2'] * n_classes, kernel_size=3, padding=1)
        self.cl_conv11_2 = nn.Conv2d(256, n_boxes['conv11_2'] * n_classes, kernel_size=3, padding=1)

        # Initialize convolutions' parameters
        self.init_conv2d()

    def init_conv2d(self):
        """
        Initialize convolution parameters.
        """
        for c in self.children():
            if isinstance(c, nn.Conv2d):
                nn.init.xavier_uniform_(c.weight)
                nn.init.constant_(c.bias, 0.)

    def forward(self, conv4_3_feats, conv7_feats, conv8_2_feats, conv9_2_feats, conv10_2_feats, conv11_2_feats):
        """
        Forward propagation.

        :param conv4_3_feats: conv4_3 feature map, a tensor of dimensions (N, 512, 38, 38)
        :param conv7_feats: conv7 feature map, a tensor of dimensions (N, 1024, 19, 19)
        :param conv8_2_feats: conv8_2 feature map, a tensor of dimensions (N, 512, 10, 10)
        :param conv9_2_feats: conv9_2 feature map, a tensor of dimensions (N, 256, 5, 5)
        :param conv10_2_feats: conv10_2 feature map, a tensor of dimensions (N, 256, 3, 3)
        :param conv11_2_feats: conv11_2 feature map, a tensor of dimensions (N, 256, 1, 1)
        :return: 8732 locations and class scores (i.e. w.r.t each prior box) for each image
        """
        batch_size = conv4_3_feats.size(0)

        # Predict localization boxes' bounds (as offsets w.r.t prior-boxes)
        l_conv4_3 = self.loc_conv4_3(conv4_3_feats)  # (N, 16, 38, 38)
        l_conv4_3 = l_conv4_3.permute(0, 2, 3,
                                      1).contiguous()  # (N, 38, 38, 16), to match prior-box order (after .view())
        # (.contiguous() ensures it is stored in a contiguous chunk of memory, needed for .view() below)
        l_conv4_3 = l_conv4_3.view(batch_size, -1, 4)  # (N, 5776, 4), there are a total 5776 boxes on this feature map

        l_conv7 = self.loc_conv7(conv7_feats)  # (N, 24, 19, 19)
        l_conv7 = l_conv7.permute(0, 2, 3, 1).contiguous()  # (N, 19, 19, 24)
        l_conv7 = l_conv7.view(batch_size, -1, 4)  # (N, 2166, 4), there are a total 2116 boxes on this feature map

        l_conv8_2 = self.loc_conv8_2(conv8_2_feats)  # (N, 24, 10, 10)
        l_conv8_2 = l_conv8_2.permute(0, 2, 3, 1).contiguous()  # (N, 10, 10, 24)
        l_conv8_2 = l_conv8_2.view(batch_size, -1, 4)  # (N, 600, 4)

        l_conv9_2 = self.loc_conv9_2(conv9_2_feats)  # (N, 24, 5, 5)
        l_conv9_2 = l_conv9_2.permute(0, 2, 3, 1).contiguous()  # (N, 5, 5, 24)
        l_conv9_2 = l_conv9_2.view(batch_size, -1, 4)  # (N, 150, 4)

        l_conv10_2 = self.loc_conv10_2(conv10_2_feats)  # (N, 16, 3, 3)
        l_conv10_2 = l_conv10_2.permute(0, 2, 3, 1).contiguous()  # (N, 3, 3, 16)
        l_conv10_2 = l_conv10_2.view(batch_size, -1, 4)  # (N, 36, 4)

        l_conv11_2 = self.loc_conv11_2(conv11_2_feats)  # (N, 16, 1, 1)
        l_conv11_2 = l_conv11_2.permute(0, 2, 3, 1).contiguous()  # (N, 1, 1, 16)
        l_conv11_2 = l_conv11_2.view(batch_size, -1, 4)  # (N, 4, 4)

        # Predict classes in localization boxes
        c_conv4_3 = self.cl_conv4_3(conv4_3_feats)  # (N, 4 * n_classes, 38, 38)
        c_conv4_3 = c_conv4_3.permute(0, 2, 3,
                                      1).contiguous()  # (N, 38, 38, 4 * n_classes), to match prior-box order (after .view())
        c_conv4_3 = c_conv4_3.view(batch_size, -1,
                                   self.n_classes)  # (N, 5776, n_classes), there are a total 5776 boxes on this feature map

        c_conv7 = self.cl_conv7(conv7_feats)  # (N, 6 * n_classes, 19, 19)
        c_conv7 = c_conv7.permute(0, 2, 3, 1).contiguous()  # (N, 19, 19, 6 * n_classes)
        c_conv7 = c_conv7.view(batch_size, -1,
                               self.n_classes)  # (N, 2166, n_classes), there are a total 2116 boxes on this feature map

        c_conv8_2 = self.cl_conv8_2(conv8_2_feats)  # (N, 6 * n_classes, 10, 10)
        c_conv8_2 = c_conv8_2.permute(0, 2, 3, 1).contiguous()  # (N, 10, 10, 6 * n_classes)
        c_conv8_2 = c_conv8_2.view(batch_size, -1, self.n_classes)  # (N, 600, n_classes)

        c_conv9_2 = self.cl_conv9_2(conv9_2_feats)  # (N, 6 * n_classes, 5, 5)
        c_conv9_2 = c_conv9_2.permute(0, 2, 3, 1).contiguous()  # (N, 5, 5, 6 * n_classes)
        c_conv9_2 = c_conv9_2.view(batch_size, -1, self.n_classes)  # (N, 150, n_classes)

        c_conv10_2 = self.cl_conv10_2(conv10_2_feats)  # (N, 4 * n_classes, 3, 3)
        c_conv10_2 = c_conv10_2.permute(0, 2, 3, 1).contiguous()  # (N, 3, 3, 4 * n_classes)
        c_conv10_2 = c_conv10_2.view(batch_size, -1, self.n_classes)  # (N, 36, n_classes)

        c_conv11_2 = self.cl_conv11_2(conv11_2_feats)  # (N, 4 * n_classes, 1, 1)
        c_conv11_2 = c_conv11_2.permute(0, 2, 3, 1).contiguous()  # (N, 1, 1, 4 * n_classes)
        c_conv11_2 = c_conv11_2.view(batch_size, -1, self.n_classes)  # (N, 4, n_classes)

        # A total of 8732 boxes
        # Concatenate in this specific order (i.e. must match the order of the prior-boxes)
        locs = torch.cat([l_conv4_3, l_conv7, l_conv8_2, l_conv9_2, l_conv10_2, l_conv11_2], dim=1)  # (N, 8732, 4)
        classes_scores = torch.cat([c_conv4_3, c_conv7, c_conv8_2, c_conv9_2, c_conv10_2, c_conv11_2],
                                   dim=1)  # (N, 8732, n_classes)

        return locs, classes_scores

The SSD300 Model

init - Defines all network layers and created prior boxes

create_prior_boxes - Create 8732 prior boxes across the 6 feature maps

forward - Send the input data through the three network components and then return the predicted locations and classification scores.

detect_objects - After a forward pass the predicted objects can be sent to this function during testing in order to perform NMS for the final output.

Answer the follwowing questions after reading the NMS code and comparing it to the version in the lecture notes / tutorial.

  1. What variables within the batch_size for loop represent "D" and "$\bar{B}$"?

The variables representing "D" is all_images_boxes for all classes or image_boxes for a single class. This variable contains the final detections that has no duplicates. The variable representing "$\bar{B}$" is class_decoded_locs. It contains our initial set of duplicate boxes.

  1. The NMS psuedo code is written with operations such as union and set subtraction. Within the NMS python code how are boxes selected in order to be added to the "D" output?

The sorted boxes are iterated, and we keep a torch.uint8 (byte) tensor to keep track of which predicted boxes to suppress (1 implies suppress, 0 implies don't suppress). This is the way the code represent subtraction. We supress boxes that overlaps with current box greater than the threshold. At the end of iteration, we simply take boxes that aren't marked as supressed as the output D that we append to images_boxes.

In [12]:
class SSD300(nn.Module):
    """
    The SSD300 network - encapsulates the base network, auxiliary, and prediction convolutions.
    """

    def __init__(self, n_classes, base_type):
        super(SSD300, self).__init__()

        self.n_classes = n_classes

        if base_type == 'VGG':
          self.base = VGGBase()
        elif base_type == 'ResNet':
          self.base = ResNetBase()
        else:
          raise NotImplementedError
        self.aux_convs = AuxiliaryConvolutions()
        self.pred_convs = PredictionConvolutions(n_classes)

        # Since lower level features (conv4_3_feats) have considerably larger scales, we take the L2 norm and rescale
        # Rescale factor is initially set at 20, but is learned for each channel during back-prop
        self.rescale_factors = nn.Parameter(torch.FloatTensor(1, 512, 1, 1))  # there are 512 channels in conv4_3_feats
        nn.init.constant_(self.rescale_factors, 20)

        # Prior boxes
        self.priors_cxcy = self.create_prior_boxes()

    def forward(self, image):
        """
        Forward propagation.

        :param image: images, a tensor of dimensions (N, 3, 300, 300)
        :return: 8732 locations and class scores (i.e. w.r.t each prior box) for each image
        """
        # Run VGG base network convolutions (lower level feature map generators)
        conv4_3_feats, conv7_feats = self.base(image)  # (N, 512, 38, 38), (N, 1024, 19, 19)

        # Rescale conv4_3 after L2 norm
        norm = conv4_3_feats.pow(2).sum(dim=1, keepdim=True).sqrt()  # (N, 1, 38, 38)
        conv4_3_feats = conv4_3_feats / norm  # (N, 512, 38, 38)
        conv4_3_feats = conv4_3_feats * self.rescale_factors  # (N, 512, 38, 38)
        # (PyTorch autobroadcasts singleton dimensions during arithmetic)

        # Run auxiliary convolutions (higher level feature map generators)
        conv8_2_feats, conv9_2_feats, conv10_2_feats, conv11_2_feats = \
            self.aux_convs(conv7_feats)  # (N, 512, 10, 10),  (N, 256, 5, 5), (N, 256, 3, 3), (N, 256, 1, 1)

        # Run prediction convolutions (predict offsets w.r.t prior-boxes and classes in each resulting localization box)
        locs, classes_scores = self.pred_convs(conv4_3_feats, conv7_feats, conv8_2_feats, conv9_2_feats, conv10_2_feats,
                                               conv11_2_feats)  # (N, 8732, 4), (N, 8732, n_classes)

        return locs, classes_scores

    def create_prior_boxes(self):
        """
        Create the 8732 prior (default) boxes for the SSD300, as defined in the paper.

        :return: prior boxes in center-size coordinates, a tensor of dimensions (8732, 4)
        """
        fmap_dims = {'conv4_3': 38,
                     'conv7': 19,
                     'conv8_2': 10,
                     'conv9_2': 5,
                     'conv10_2': 3,
                     'conv11_2': 1}

        obj_scales = {'conv4_3': 0.1,
                      'conv7': 0.2,
                      'conv8_2': 0.375,
                      'conv9_2': 0.55,
                      'conv10_2': 0.725,
                      'conv11_2': 0.9}

        aspect_ratios = {'conv4_3': [1., 2., 0.5],
                         'conv7': [1., 2., 3., 0.5, .333],
                         'conv8_2': [1., 2., 3., 0.5, .333],
                         'conv9_2': [1., 2., 3., 0.5, .333],
                         'conv10_2': [1., 2., 0.5],
                         'conv11_2': [1., 2., 0.5]}

        fmaps = list(fmap_dims.keys())

        prior_boxes = []

        for k, fmap in enumerate(fmaps):
            for i in range(fmap_dims[fmap]):
                for j in range(fmap_dims[fmap]):
                    cx = (j + 0.5) / fmap_dims[fmap]
                    cy = (i + 0.5) / fmap_dims[fmap]

                    for ratio in aspect_ratios[fmap]:
                        prior_boxes.append([cx, cy, obj_scales[fmap] * sqrt(ratio), obj_scales[fmap] / sqrt(ratio)])

                        # For an aspect ratio of 1, use an additional prior whose scale is the geometric mean of the
                        # scale of the current feature map and the scale of the next feature map
                        if ratio == 1.:
                            try:
                                additional_scale = sqrt(obj_scales[fmap] * obj_scales[fmaps[k + 1]])
                            # For the last feature map, there is no "next" feature map
                            except IndexError:
                                additional_scale = 1.
                            prior_boxes.append([cx, cy, additional_scale, additional_scale])

        prior_boxes = torch.FloatTensor(prior_boxes).to(device)  # (8732, 4)
        prior_boxes.clamp_(0, 1)  # (8732, 4)

        return prior_boxes

    def detect_objects(self, predicted_locs, predicted_scores, min_score, max_overlap, top_k):
        """
        Decipher the 8732 locations and class scores (output of ths SSD300) to detect objects.

        For each class, perform Non-Maximum Suppression (NMS) on boxes that are above a minimum threshold.

        :param predicted_locs: predicted locations/boxes w.r.t the 8732 prior boxes, a tensor of dimensions (N, 8732, 4)
        :param predicted_scores: class scores for each of the encoded locations/boxes, a tensor of dimensions (N, 8732, n_classes)
        :param min_score: minimum threshold for a box to be considered a match for a certain class
        :param max_overlap: maximum overlap two boxes can have so that the one with the lower score is not suppressed via NMS
        :param top_k: if there are a lot of resulting detection across all classes, keep only the top 'k'
        :return: detections (boxes, labels, and scores), lists of length batch_size
        """
        batch_size = predicted_locs.size(0)
        n_priors = self.priors_cxcy.size(0)
        predicted_scores = F.softmax(predicted_scores, dim=2)  # (N, 8732, n_classes)

        # Lists to store final predicted boxes, labels, and scores for all images
        all_images_boxes = list()
        all_images_labels = list()
        all_images_scores = list()

        assert n_priors == predicted_locs.size(1) == predicted_scores.size(1)

        for i in range(batch_size):
            # Decode object coordinates from the form we regressed predicted boxes to
            decoded_locs = cxcy_to_xy(
                gcxgcy_to_cxcy(predicted_locs[i], self.priors_cxcy))  # (8732, 4), these are fractional pt. coordinates

            # Lists to store boxes and scores for this image
            image_boxes = list()
            image_labels = list()
            image_scores = list()

            max_scores, best_label = predicted_scores[i].max(dim=1)  # (8732)

            # Check for each class
            for c in range(1, self.n_classes):
                # Keep only predicted boxes and scores where scores for this class are above the minimum score
                class_scores = predicted_scores[i][:, c]  # (8732)
                score_above_min_score = class_scores > min_score  # torch.uint8 (byte) tensor, for indexing
                n_above_min_score = score_above_min_score.sum().item()
                if n_above_min_score == 0:
                    continue
                class_scores = class_scores[score_above_min_score]  # (n_qualified), n_min_score <= 8732
                class_decoded_locs = decoded_locs[score_above_min_score]  # (n_qualified, 4)

                # Sort predicted boxes and scores by scores
                class_scores, sort_ind = class_scores.sort(dim=0, descending=True)  # (n_qualified), (n_min_score)
                class_decoded_locs = class_decoded_locs[sort_ind]  # (n_min_score, 4)

                # Find the overlap between predicted boxes
                overlap = find_jaccard_overlap(class_decoded_locs, class_decoded_locs)  # (n_qualified, n_min_score)

                # Non-Maximum Suppression (NMS)

                # A torch.uint8 (byte) tensor to keep track of which predicted boxes to suppress
                # 1 implies suppress, 0 implies don't suppress
                suppress = torch.zeros((n_above_min_score), dtype=torch.uint8).to(device)  # (n_qualified)

                # Consider each box in order of decreasing scores
                for box in range(class_decoded_locs.size(0)):
                    # If this box is already marked for suppression
                    if suppress[box] == 1:
                        continue

                    # Suppress boxes whose overlaps (with this box) are greater than maximum overlap
                    # Find such boxes and update suppress indices
                    suppress = torch.max(suppress, overlap[box] > max_overlap)
                    # The max operation retains previously suppressed boxes, like an 'OR' operation

                    # Don't suppress this box, even though it has an overlap of 1 with itself
                    suppress[box] = 0

                # Store only unsuppressed boxes for this class
                image_boxes.append(class_decoded_locs[1 - suppress])
                image_labels.append(torch.LongTensor((1 - suppress).sum().item() * [c]).to(device))
                image_scores.append(class_scores[1 - suppress])

            # If no object in any class is found, store a placeholder for 'background'
            if len(image_boxes) == 0:
                image_boxes.append(torch.FloatTensor([[0., 0., 1., 1.]]).to(device))
                image_labels.append(torch.LongTensor([0]).to(device))
                image_scores.append(torch.FloatTensor([0.]).to(device))

            # Concatenate into single tensors
            image_boxes = torch.cat(image_boxes, dim=0)  # (n_objects, 4)
            image_labels = torch.cat(image_labels, dim=0)  # (n_objects)
            image_scores = torch.cat(image_scores, dim=0)  # (n_objects)
            n_objects = image_scores.size(0)

            # Keep only the top k objects
            if n_objects > top_k:
                image_scores, sort_ind = image_scores.sort(dim=0, descending=True)
                image_scores = image_scores[:top_k]  # (top_k)
                image_boxes = image_boxes[sort_ind][:top_k]  # (top_k, 4)
                image_labels = image_labels[sort_ind][:top_k]  # (top_k)

            # Append to lists that store predicted boxes and scores for all images
            all_images_boxes.append(image_boxes)
            all_images_labels.append(image_labels)
            all_images_scores.append(image_scores)

        return all_images_boxes, all_images_labels, all_images_scores  # lists of length batch_size

The MultiBoxLoss

During training the output from the SSD forward pass is then sent to the criterion (set to this function) in order to calculate the loss.

In [13]:
class MultiBoxLoss(nn.Module):
    """
    The MultiBox loss, a loss function for object detection.

    This is a combination of:
    (1) a localization loss for the predicted locations of the boxes, and
    (2) a confidence loss for the predicted class scores.
    """

    def __init__(self, priors_cxcy, threshold=0.5, neg_pos_ratio=3, alpha=1.):
        super(MultiBoxLoss, self).__init__()
        self.priors_cxcy = priors_cxcy
        self.priors_xy = cxcy_to_xy(priors_cxcy)
        self.threshold = threshold
        self.neg_pos_ratio = neg_pos_ratio
        self.alpha = alpha

        self.smooth_l1 = nn.L1Loss()
        self.cross_entropy = nn.CrossEntropyLoss(reduce=False)

    def forward(self, predicted_locs, predicted_scores, boxes, labels):
        """
        Forward propagation.

        :param predicted_locs: predicted locations/boxes w.r.t the 8732 prior boxes, a tensor of dimensions (N, 8732, 4)
        :param predicted_scores: class scores for each of the encoded locations/boxes, a tensor of dimensions (N, 8732, n_classes)
        :param boxes: true  object bounding boxes in boundary coordinates, a list of N tensors
        :param labels: true object labels, a list of N tensors
        :return: multibox loss, a scalar
        """
        batch_size = predicted_locs.size(0)
        n_priors = self.priors_cxcy.size(0)
        n_classes = predicted_scores.size(2)

        assert n_priors == predicted_locs.size(1) == predicted_scores.size(1)

        true_locs = torch.zeros((batch_size, n_priors, 4), dtype=torch.float).to(device)  # (N, 8732, 4)
        true_classes = torch.zeros((batch_size, n_priors), dtype=torch.long).to(device)  # (N, 8732)

        # For each image
        for i in range(batch_size):
            n_objects = boxes[i].size(0)

            overlap = find_jaccard_overlap(boxes[i],
                                           self.priors_xy)  # (n_objects, 8732)

            # For each prior, find the object that has the maximum overlap
            overlap_for_each_prior, object_for_each_prior = overlap.max(dim=0)  # (8732)

            # We don't want a situation where an object is not represented in our positive (non-background) priors -
            # 1. An object might not be the best object for all priors, and is therefore not in object_for_each_prior.
            # 2. All priors with the object may be assigned as background based on the threshold (0.5).

            # To remedy this -
            # First, find the prior that has the maximum overlap for each object.
            _, prior_for_each_object = overlap.max(dim=1)  # (N_o)

            # Then, assign each object to the corresponding maximum-overlap-prior. (This fixes 1.)
            object_for_each_prior[prior_for_each_object] = torch.LongTensor(range(n_objects)).to(device)

            # To ensure these priors qualify, artificially give them an overlap of greater than 0.5. (This fixes 2.)
            overlap_for_each_prior[prior_for_each_object] = 1.

            # Labels for each prior
            label_for_each_prior = labels[i][object_for_each_prior]  # (8732)
            # Set priors whose overlaps with objects are less than the threshold to be background (no object)
            label_for_each_prior[overlap_for_each_prior < self.threshold] = 0  # (8732)

            # Store
            true_classes[i] = label_for_each_prior

            # Encode center-size object coordinates into the form we regressed predicted boxes to
            true_locs[i] = cxcy_to_gcxgcy(xy_to_cxcy(boxes[i][object_for_each_prior]), self.priors_cxcy)  # (8732, 4)

        # Identify priors that are positive (object/non-background)
        positive_priors = true_classes != 0  # (N, 8732)

        # LOCALIZATION LOSS

        # Localization loss is computed only over positive (non-background) priors
        loc_loss = self.smooth_l1(predicted_locs[positive_priors], true_locs[positive_priors])  # (), scalar

        # Note: indexing with a torch.uint8 (byte) tensor flattens the tensor when indexing is across multiple dimensions (N & 8732)
        # So, if predicted_locs has the shape (N, 8732, 4), predicted_locs[positive_priors] will have (total positives, 4)

        # CONFIDENCE LOSS

        # Confidence loss is computed over positive priors and the most difficult (hardest) negative priors in each image
        # That is, FOR EACH IMAGE,
        # we will take the hardest (neg_pos_ratio * n_positives) negative priors, i.e where there is maximum loss
        # This is called Hard Negative Mining - it concentrates on hardest negatives in each image, and also minimizes pos/neg imbalance

        # Number of positive and hard-negative priors per image
        n_positives = positive_priors.sum(dim=1)  # (N)
        n_hard_negatives = self.neg_pos_ratio * n_positives  # (N)

        # First, find the loss for all priors
        conf_loss_all = self.cross_entropy(predicted_scores.view(-1, n_classes), true_classes.view(-1))  # (N * 8732)
        conf_loss_all = conf_loss_all.view(batch_size, n_priors)  # (N, 8732)

        # We already know which priors are positive
        conf_loss_pos = conf_loss_all[positive_priors]  # (sum(n_positives))

        # Next, find which priors are hard-negative
        # To do this, sort ONLY negative priors in each image in order of decreasing loss and take top n_hard_negatives
        conf_loss_neg = conf_loss_all.clone()  # (N, 8732)
        conf_loss_neg[positive_priors] = 0.  # (N, 8732), positive priors are ignored (never in top n_hard_negatives)
        conf_loss_neg, _ = conf_loss_neg.sort(dim=1, descending=True)  # (N, 8732), sorted by decreasing hardness
        hardness_ranks = torch.LongTensor(range(n_priors)).unsqueeze(0).expand_as(conf_loss_neg).to(device)  # (N, 8732)
        hard_negatives = hardness_ranks < n_hard_negatives.unsqueeze(1)  # (N, 8732)
        conf_loss_hard_neg = conf_loss_neg[hard_negatives]  # (sum(n_hard_negatives))

        # As in the paper, averaged over positive priors only, although computed over both positive and hard-negative priors
        conf_loss = (conf_loss_hard_neg.sum() + conf_loss_pos.sum()) / n_positives.sum().float()  # (), scalar

        # TOTAL LOSS
        return conf_loss + self.alpha * loc_loss

Training

With the model implemented it is time to train. Should take 2 hours and 9 minutes for 10 epochs. Should take 1 hour and 5 minutes for only the VOC2007 dataset with 16 epochs.

In [19]:
import time
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
# from model import SSD300, MultiBoxLoss
# from datasets import PascalVOCDataset
from utils import *
# TODO: Import a learning rate scheduler
from torch.optim.lr_scheduler import MultiStepLR

# Data parameters
data_folder = './'  # folder with data files
keep_difficult = True  # use objects considered difficult to detect?

# Model parameters
# Not too many here since the SSD300 has a very specific structure
n_classes = len(label_map)  # number of different types of objects
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# Learning parameters
checkpoint = None  # path to model checkpoint, None if none
batch_size = 6  # batch size
iterations = 15000 # 120000  # number of iterations to train (DON'T CHANGE)
workers = 4  # number of workers for loading data in the DataLoader
print_freq = 200  # print training status every __ batches
momentum = 0.9  # momentum
weight_decay = 5e-4  # weight decay
grad_clip = None  # clip if gradients are exploding, which may happen at larger batch sizes (sometimes at 32) - you will recognize it by a sorting error in the MuliBox loss calculation

cudnn.benchmark = True

# Overwrite the checkpoint function in utils
def save_checkpoint(epoch, model, optimizer, base_type, scheduler):
    """
    Save model checkpoint.

    :param epoch: epoch number
    :param model: model
    :param optimizer: optimizer
    :param base_type: The base network type
    :param scheduler: scheduler
    """
    state = {'epoch': epoch,
             'model': model,
             'optimizer': optimizer,
             'scheduler': scheduler}
    if scheduler == None:
      filename = 'checkpoint_ssd300_' + base_type + '.pth.tar'
    else:
      filename = 'checkpoint_ssd300_' + base_type + '_scheduler.pth.tar'
    torch.save(state, filename)

def train_SSD(base_type, lr_type):
    """
    Training.
    """
    global start_epoch, label_map, epoch, checkpoint, decay_lr_at

    # Custom dataloaders
    train_dataset = PascalVOCDataset(data_folder,
                                     split='train',
                                     keep_difficult=keep_difficult)
    train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True,
                                               collate_fn=train_dataset.collate_fn, num_workers=workers,
                                               pin_memory=True)  # note that we're passing the collate function here

    if lr_type == 'original_scheduler':
      lr = 1e-3  # learning rate
      decay_lr_at = [10000, 12500] # [80000, 100000]  # decay learning rate after these many iterations
      decay_lr_to = 0.1  # decay learning rate to this fraction of the existing learning rate
    elif lr_type == 'pytorch_scheduler':
      lr = 1e-3 # learning rate
    else:
      raise NotImplementedError

    # Calculate total number of epochs to train and the epochs to decay learning rate at (i.e. convert iterations to epochs)
    # To convert iterations to epochs, divide iterations by the number of iterations per epoch
    # The original paper trains for 120,000 iterations with a batch size of 32, decays after 80,000 and 100,000 iterations
    epochs = iterations // (len(train_dataset) // batch_size)
    print("Number of iterations", iterations)
    print("Dataset length", len(train_dataset))
    print("batch size", batch_size)
    print("Number of Epochs to train:", epochs)

    if lr_type == 'original_scheduler':
      decay_lr_at = [it // (len(train_dataset) // batch_size) for it in decay_lr_at]
      print("Epochs to decay learning rate:", decay_lr_at)

    # Initialize model or load checkpoint
    if checkpoint is None:
        start_epoch = 0
        model = SSD300(n_classes=n_classes, base_type=base_type)
        # Initialize the optimizer, with twice the default learning rate for biases, as in the original Caffe repo
        biases = list()
        not_biases = list()
        for param_name, param in model.named_parameters():
            if param.requires_grad:
                if param_name.endswith('.bias'):
                    biases.append(param)
                else:
                    not_biases.append(param)
        optimizer = torch.optim.SGD(params=[{'params': biases, 'lr': 2 * lr}, {'params': not_biases}],
                                    lr=lr, momentum=momentum, weight_decay=weight_decay)
        if lr_type == 'pytorch_scheduler':
          # TODO: Create new scheduler
          # decay_lr_at = [it // (len(train_dataset) // batch_size) for it in [int(0.6*iterations), int(0.8*iterations)]] # decay at epochs when 30% and 30% of iterations are complete
          scheduler = MultiStepLR(optimizer, milestones=[epochs*0.6, epochs*0.8], gamma=0.1)
    else:
        checkpoint = torch.load(checkpoint)
        start_epoch = checkpoint['epoch'] + 1
        print('\nLoaded checkpoint from epoch %d.\n' % start_epoch)
        model = checkpoint['model']
        optimizer = checkpoint['optimizer']
        if lr_type == 'pytorch_scheduler':
          # TODO: Load scheduler
          scheduler = checkpoint['scheduler']

    # Move to default device
    model = model.to(device)
    criterion = MultiBoxLoss(priors_cxcy=model.priors_cxcy).to(device)

    # Epochs
    for epoch in range(start_epoch, epochs):

        # Decay learning rate at particular epochs
        if lr_type == 'original_scheduler':
          if epoch in decay_lr_at:
              adjust_learning_rate(optimizer, decay_lr_to)

        # One epoch's training
        start_epoch_time = time.time()
        train(train_loader=train_loader,
              model=model,
              criterion=criterion,
              optimizer=optimizer,
              epoch=epoch)
        end_epoch_time = time.time()
        print("One epoch time elapsed:", end_epoch_time - start_epoch_time)
        
        # TODO: Update the learning rate
        if lr_type == 'pytorch_scheduler':
          scheduler.step()

        # Save checkpoint
        if lr_type == 'original_scheduler':
          save_checkpoint(epoch, model, optimizer, base_type, scheduler=None)
        else:
          # TODO: Call save_checkpoint with your scheduler
          save_checkpoint(epoch, model, optimizer, base_type, scheduler=scheduler)

def train(train_loader, model, criterion, optimizer, epoch):
    """
    One epoch's training.
    :param train_loader: DataLoader for training data
    :param model: model
    :param criterion: MultiBox loss
    :param optimizer: optimizer
    :param epoch: epoch number
    """
    model.train()  # training mode enables dropout

    batch_time = AverageMeter()  # forward prop. + back prop. time
    data_time = AverageMeter()  # data loading time
    losses = AverageMeter()  # loss

    start = time.time()

    # Batches
    for i, (images, boxes, labels, _) in enumerate(train_loader):
        data_time.update(time.time() - start)

        # Move to default device
        images = images.to(device)  # (batch_size (N), 3, 300, 300)
        boxes = [b.to(device) for b in boxes]
        labels = [l.to(device) for l in labels]

        # Forward prop.
        predicted_locs, predicted_scores = model(images)  # (N, 8732, 4), (N, 8732, n_classes)

        # Loss
        loss = criterion(predicted_locs, predicted_scores, boxes, labels)  # scalar

        # Backward prop.
        optimizer.zero_grad()
        loss.backward()

        # Clip gradients, if necessary
        if grad_clip is not None:
            clip_gradient(optimizer, grad_clip)

        # Update model
        optimizer.step()

        losses.update(loss.item(), images.size(0))
        batch_time.update(time.time() - start)

        start = time.time()

        # Print status
        if i % print_freq == 0:
            print('Epoch: [{0}][{1}/{2}]\t'
                  'Batch Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
                  'Data Time {data_time.val:.3f} ({data_time.avg:.3f})\t'
                  'Loss {loss.val:.4f} ({loss.avg:.4f})\t'.format(epoch, i, len(train_loader),
                                                                  batch_time=batch_time,
                                                                  data_time=data_time, loss=losses))
    del predicted_locs, predicted_scores, images, boxes, labels  # free some memory since their histories may be stored

Training SSD300 with VGG and the original learning rate adjuster

This can be run without making any changes to the code.

In [12]:
start_time = time.time()
train_SSD(base_type='VGG', lr_type='original_scheduler')
end_time = time.time()
print("time elapsed:", end_time - start_time)
Number of iterations 15000
Dataset length 5011
batch size 6
Number of Epochs to train: 17
Epochs to decay learning rate: [11, 14]
Downloading: "https://download.pytorch.org/models/vgg16-397923af.pth" to /root/.cache/torch/hub/checkpoints/vgg16-397923af.pth

Loaded base model.

/usr/local/lib/python3.7/dist-packages/torch/nn/_reduction.py:44: UserWarning: size_average and reduce args will be deprecated, please use reduction='none' instead.
  warnings.warn(warning.format(ret))
Epoch: [0][0/836]	Batch Time 81.086 (81.086)	Data Time 77.760 (77.760)	Loss 23.9627 (23.9627)	
Epoch: [0][200/836]	Batch Time 1.283 (0.947)	Data Time 1.034 (0.691)	Loss 7.1553 (11.0960)	
Epoch: [0][400/836]	Batch Time 1.021 (0.743)	Data Time 0.777 (0.490)	Loss 6.3579 (8.7239)	
Epoch: [0][600/836]	Batch Time 1.126 (0.665)	Data Time 0.882 (0.412)	Loss 5.8544 (7.8673)	
Epoch: [0][800/836]	Batch Time 1.353 (0.625)	Data Time 1.108 (0.373)	Loss 6.0109 (7.3907)	
One epoch time elapsed: 519.5479884147644
Epoch: [1][0/836]	Batch Time 1.395 (1.395)	Data Time 1.037 (1.037)	Loss 5.4361 (5.4361)	
Epoch: [1][200/836]	Batch Time 0.248 (0.276)	Data Time 0.000 (0.006)	Loss 5.5271 (5.7885)	
Epoch: [1][400/836]	Batch Time 0.274 (0.273)	Data Time 0.001 (0.004)	Loss 6.3090 (5.7661)	
Epoch: [1][600/836]	Batch Time 0.258 (0.271)	Data Time 0.000 (0.003)	Loss 4.5791 (5.7017)	
Epoch: [1][800/836]	Batch Time 0.268 (0.270)	Data Time 0.001 (0.002)	Loss 5.6313 (5.6335)	
One epoch time elapsed: 225.33653116226196
Epoch: [2][0/836]	Batch Time 1.633 (1.633)	Data Time 1.293 (1.293)	Loss 6.6259 (6.6259)	
Epoch: [2][200/836]	Batch Time 0.279 (0.277)	Data Time 0.000 (0.007)	Loss 5.5661 (5.3943)	
Epoch: [2][400/836]	Batch Time 0.275 (0.272)	Data Time 0.016 (0.004)	Loss 5.2031 (5.3195)	
Epoch: [2][600/836]	Batch Time 0.250 (0.270)	Data Time 0.000 (0.003)	Loss 5.4527 (5.2423)	
Epoch: [2][800/836]	Batch Time 0.271 (0.269)	Data Time 0.000 (0.002)	Loss 4.5980 (5.2152)	
One epoch time elapsed: 224.54358172416687
Epoch: [3][0/836]	Batch Time 1.419 (1.419)	Data Time 1.070 (1.070)	Loss 4.4982 (4.4982)	
Epoch: [3][200/836]	Batch Time 0.267 (0.276)	Data Time 0.000 (0.006)	Loss 4.4040 (4.9542)	
Epoch: [3][400/836]	Batch Time 0.252 (0.271)	Data Time 0.000 (0.003)	Loss 5.3206 (4.9262)	
Epoch: [3][600/836]	Batch Time 0.254 (0.269)	Data Time 0.004 (0.003)	Loss 4.4426 (4.8890)	
Epoch: [3][800/836]	Batch Time 0.266 (0.269)	Data Time 0.000 (0.002)	Loss 6.2048 (4.8637)	
One epoch time elapsed: 224.74311089515686
Epoch: [4][0/836]	Batch Time 1.742 (1.742)	Data Time 1.406 (1.406)	Loss 4.4027 (4.4027)	
Epoch: [4][200/836]	Batch Time 0.303 (0.279)	Data Time 0.000 (0.008)	Loss 4.6168 (4.6913)	
Epoch: [4][400/836]	Batch Time 0.282 (0.274)	Data Time 0.005 (0.004)	Loss 4.6135 (4.6404)	
Epoch: [4][600/836]	Batch Time 0.277 (0.271)	Data Time 0.000 (0.003)	Loss 5.1089 (4.5972)	
Epoch: [4][800/836]	Batch Time 0.276 (0.269)	Data Time 0.000 (0.002)	Loss 4.4143 (4.5816)	
One epoch time elapsed: 224.83513474464417
Epoch: [5][0/836]	Batch Time 1.254 (1.254)	Data Time 0.897 (0.897)	Loss 4.4377 (4.4377)	
Epoch: [5][200/836]	Batch Time 0.298 (0.274)	Data Time 0.000 (0.005)	Loss 6.7254 (4.4154)	
Epoch: [5][400/836]	Batch Time 0.284 (0.271)	Data Time 0.005 (0.003)	Loss 3.8775 (4.4172)	
Epoch: [5][600/836]	Batch Time 0.250 (0.270)	Data Time 0.000 (0.002)	Loss 4.7378 (4.3803)	
Epoch: [5][800/836]	Batch Time 0.276 (0.269)	Data Time 0.000 (0.002)	Loss 3.2830 (4.3598)	
One epoch time elapsed: 224.24707746505737
Epoch: [6][0/836]	Batch Time 1.418 (1.418)	Data Time 1.041 (1.041)	Loss 4.3550 (4.3550)	
Epoch: [6][200/836]	Batch Time 0.264 (0.272)	Data Time 0.000 (0.006)	Loss 4.0931 (4.1650)	
Epoch: [6][400/836]	Batch Time 0.260 (0.269)	Data Time 0.000 (0.003)	Loss 4.8657 (4.2229)	
Epoch: [6][600/836]	Batch Time 0.263 (0.269)	Data Time 0.000 (0.002)	Loss 4.1641 (4.2059)	
Epoch: [6][800/836]	Batch Time 0.267 (0.268)	Data Time 0.000 (0.002)	Loss 4.4020 (4.1798)	
One epoch time elapsed: 223.5859968662262
Epoch: [7][0/836]	Batch Time 1.071 (1.071)	Data Time 0.770 (0.770)	Loss 4.0637 (4.0637)	
Epoch: [7][200/836]	Batch Time 0.261 (0.276)	Data Time 0.000 (0.008)	Loss 5.3262 (4.1415)	
Epoch: [7][400/836]	Batch Time 0.257 (0.271)	Data Time 0.000 (0.004)	Loss 4.8661 (4.1158)	
Epoch: [7][600/836]	Batch Time 0.258 (0.269)	Data Time 0.000 (0.003)	Loss 4.0390 (4.1032)	
Epoch: [7][800/836]	Batch Time 0.280 (0.269)	Data Time 0.000 (0.003)	Loss 3.0134 (4.0837)	
One epoch time elapsed: 224.51391649246216
Epoch: [8][0/836]	Batch Time 1.303 (1.303)	Data Time 0.956 (0.956)	Loss 4.0228 (4.0228)	
Epoch: [8][200/836]	Batch Time 0.253 (0.274)	Data Time 0.000 (0.007)	Loss 3.8901 (3.9762)	
Epoch: [8][400/836]	Batch Time 0.261 (0.270)	Data Time 0.000 (0.004)	Loss 4.0710 (3.9291)	
Epoch: [8][600/836]	Batch Time 0.258 (0.269)	Data Time 0.000 (0.003)	Loss 4.1159 (3.9409)	
Epoch: [8][800/836]	Batch Time 0.269 (0.268)	Data Time 0.000 (0.002)	Loss 3.9633 (3.9372)	
One epoch time elapsed: 223.90043210983276
Epoch: [9][0/836]	Batch Time 1.012 (1.012)	Data Time 0.730 (0.730)	Loss 3.8693 (3.8693)	
Epoch: [9][200/836]	Batch Time 0.280 (0.274)	Data Time 0.005 (0.006)	Loss 3.8388 (3.8383)	
Epoch: [9][400/836]	Batch Time 0.261 (0.270)	Data Time 0.000 (0.003)	Loss 2.8732 (3.8623)	
Epoch: [9][600/836]	Batch Time 0.269 (0.269)	Data Time 0.000 (0.002)	Loss 3.6474 (3.8531)	
Epoch: [9][800/836]	Batch Time 0.271 (0.269)	Data Time 0.000 (0.002)	Loss 3.2639 (3.8646)	
One epoch time elapsed: 224.27309560775757
Epoch: [10][0/836]	Batch Time 1.170 (1.170)	Data Time 0.825 (0.825)	Loss 2.9583 (2.9583)	
Epoch: [10][200/836]	Batch Time 0.256 (0.275)	Data Time 0.000 (0.006)	Loss 3.8117 (3.8455)	
Epoch: [10][400/836]	Batch Time 0.265 (0.270)	Data Time 0.000 (0.003)	Loss 2.7325 (3.7884)	
Epoch: [10][600/836]	Batch Time 0.259 (0.268)	Data Time 0.000 (0.002)	Loss 3.1445 (3.7797)	
Epoch: [10][800/836]	Batch Time 0.253 (0.268)	Data Time 0.000 (0.002)	Loss 3.9220 (3.7706)	
One epoch time elapsed: 223.49403619766235
DECAYING learning rate.
 The new LR is 0.000100

Epoch: [11][0/836]	Batch Time 1.435 (1.435)	Data Time 1.113 (1.113)	Loss 3.8756 (3.8756)	
Epoch: [11][200/836]	Batch Time 0.273 (0.274)	Data Time 0.000 (0.006)	Loss 4.0241 (3.5292)	
Epoch: [11][400/836]	Batch Time 0.251 (0.269)	Data Time 0.000 (0.003)	Loss 3.7286 (3.4598)	
Epoch: [11][600/836]	Batch Time 0.266 (0.268)	Data Time 0.001 (0.002)	Loss 3.2945 (3.4062)	
Epoch: [11][800/836]	Batch Time 0.266 (0.267)	Data Time 0.000 (0.002)	Loss 4.1886 (3.3986)	
One epoch time elapsed: 223.0296618938446
Epoch: [12][0/836]	Batch Time 1.330 (1.330)	Data Time 0.977 (0.977)	Loss 2.6148 (2.6148)	
Epoch: [12][200/836]	Batch Time 0.274 (0.272)	Data Time 0.000 (0.005)	Loss 2.1829 (3.2968)	
Epoch: [12][400/836]	Batch Time 0.261 (0.269)	Data Time 0.000 (0.003)	Loss 3.5018 (3.3030)	
Epoch: [12][600/836]	Batch Time 0.276 (0.268)	Data Time 0.000 (0.002)	Loss 3.3547 (3.3123)	
Epoch: [12][800/836]	Batch Time 0.263 (0.268)	Data Time 0.000 (0.002)	Loss 3.5565 (3.3024)	
One epoch time elapsed: 223.31592392921448
Epoch: [13][0/836]	Batch Time 0.948 (0.948)	Data Time 0.683 (0.683)	Loss 3.5729 (3.5729)	
Epoch: [13][200/836]	Batch Time 0.253 (0.272)	Data Time 0.000 (0.005)	Loss 3.2157 (3.3374)	
Epoch: [13][400/836]	Batch Time 0.268 (0.269)	Data Time 0.000 (0.003)	Loss 2.9238 (3.3203)	
Epoch: [13][600/836]	Batch Time 0.287 (0.268)	Data Time 0.000 (0.002)	Loss 3.3847 (3.3101)	
Epoch: [13][800/836]	Batch Time 0.273 (0.268)	Data Time 0.005 (0.002)	Loss 2.8906 (3.3015)	
One epoch time elapsed: 224.15281534194946
DECAYING learning rate.
 The new LR is 0.000010

Epoch: [14][0/836]	Batch Time 2.112 (2.112)	Data Time 1.773 (1.773)	Loss 3.1477 (3.1477)	
Epoch: [14][200/836]	Batch Time 0.262 (0.278)	Data Time 0.000 (0.009)	Loss 4.3843 (3.2813)	
Epoch: [14][400/836]	Batch Time 0.265 (0.273)	Data Time 0.000 (0.005)	Loss 3.8141 (3.2564)	
Epoch: [14][600/836]	Batch Time 0.255 (0.271)	Data Time 0.000 (0.004)	Loss 2.7733 (3.2518)	
Epoch: [14][800/836]	Batch Time 0.267 (0.269)	Data Time 0.000 (0.003)	Loss 2.6660 (3.2595)	
One epoch time elapsed: 224.7086091041565
Epoch: [15][0/836]	Batch Time 1.339 (1.339)	Data Time 1.011 (1.011)	Loss 3.4302 (3.4302)	
Epoch: [15][200/836]	Batch Time 0.274 (0.272)	Data Time 0.000 (0.006)	Loss 3.4104 (3.2494)	
Epoch: [15][400/836]	Batch Time 0.271 (0.268)	Data Time 0.000 (0.004)	Loss 3.2411 (3.2596)	
Epoch: [15][600/836]	Batch Time 0.266 (0.267)	Data Time 0.000 (0.003)	Loss 3.1975 (3.2571)	
Epoch: [15][800/836]	Batch Time 0.275 (0.267)	Data Time 0.000 (0.002)	Loss 3.9220 (3.2580)	
One epoch time elapsed: 222.8652470111847
Epoch: [16][0/836]	Batch Time 1.234 (1.234)	Data Time 0.906 (0.906)	Loss 3.3033 (3.3033)	
Epoch: [16][200/836]	Batch Time 0.252 (0.273)	Data Time 0.000 (0.006)	Loss 3.2326 (3.3125)	
Epoch: [16][400/836]	Batch Time 0.257 (0.269)	Data Time 0.000 (0.003)	Loss 3.0138 (3.2965)	
Epoch: [16][600/836]	Batch Time 0.272 (0.269)	Data Time 0.020 (0.003)	Loss 3.1595 (3.2819)	
Epoch: [16][800/836]	Batch Time 0.272 (0.268)	Data Time 0.000 (0.002)	Loss 3.7080 (3.2658)	
One epoch time elapsed: 224.12099838256836
time elapsed: 4144.119537830353

Training SSD300 with ResNet and the original learning rate adjuster

This should be run after implementing the ResNet Base.

In [20]:
start_time = time.time()
train_SSD(base_type='ResNet', lr_type='original_scheduler')
end_time = time.time()
print("time elapsed:", end_time - start_time)
Number of iterations 15000
Dataset length 5011
batch size 6
Number of Epochs to train: 17
Epochs to decay learning rate: [11, 14]
/usr/local/lib/python3.7/dist-packages/torch/nn/_reduction.py:44: UserWarning: size_average and reduce args will be deprecated, please use reduction='none' instead.
  warnings.warn(warning.format(ret))
Epoch: [0][0/836]	Batch Time 1.278 (1.278)	Data Time 1.048 (1.048)	Loss 21.1355 (21.1355)	
Epoch: [0][200/836]	Batch Time 0.606 (0.238)	Data Time 0.465 (0.071)	Loss 6.5404 (10.3342)	
Epoch: [0][400/836]	Batch Time 0.211 (0.231)	Data Time 0.000 (0.065)	Loss 5.8935 (8.3062)	
Epoch: [0][600/836]	Batch Time 0.380 (0.230)	Data Time 0.221 (0.064)	Loss 5.8008 (7.5798)	
Epoch: [0][800/836]	Batch Time 0.367 (0.227)	Data Time 0.173 (0.061)	Loss 5.5284 (7.1849)	
One epoch time elapsed: 188.96977186203003
Epoch: [1][0/836]	Batch Time 1.292 (1.292)	Data Time 1.081 (1.081)	Loss 6.2276 (6.2276)	
Epoch: [1][200/836]	Batch Time 0.162 (0.228)	Data Time 0.002 (0.061)	Loss 5.8022 (5.8360)	
Epoch: [1][400/836]	Batch Time 0.149 (0.225)	Data Time 0.000 (0.059)	Loss 6.3229 (5.8598)	
Epoch: [1][600/836]	Batch Time 0.165 (0.223)	Data Time 0.000 (0.058)	Loss 5.4350 (5.8178)	
Epoch: [1][800/836]	Batch Time 0.156 (0.225)	Data Time 0.000 (0.058)	Loss 5.2632 (5.7632)	
One epoch time elapsed: 186.59940433502197
Epoch: [2][0/836]	Batch Time 1.608 (1.608)	Data Time 1.384 (1.384)	Loss 5.4951 (5.4951)	
Epoch: [2][200/836]	Batch Time 0.166 (0.234)	Data Time 0.000 (0.063)	Loss 5.7851 (5.5045)	
Epoch: [2][400/836]	Batch Time 0.331 (0.230)	Data Time 0.177 (0.059)	Loss 5.0995 (5.4571)	
Epoch: [2][600/836]	Batch Time 0.159 (0.228)	Data Time 0.000 (0.058)	Loss 5.3468 (5.4261)	
Epoch: [2][800/836]	Batch Time 0.162 (0.225)	Data Time 0.000 (0.056)	Loss 5.0272 (5.3975)	
One epoch time elapsed: 187.9539189338684
Epoch: [3][0/836]	Batch Time 1.616 (1.616)	Data Time 1.402 (1.402)	Loss 5.7094 (5.7094)	
Epoch: [3][200/836]	Batch Time 0.181 (0.233)	Data Time 0.001 (0.064)	Loss 5.1136 (5.2330)	
Epoch: [3][400/836]	Batch Time 0.257 (0.229)	Data Time 0.081 (0.061)	Loss 4.8549 (5.1550)	
Epoch: [3][600/836]	Batch Time 0.419 (0.228)	Data Time 0.263 (0.061)	Loss 4.5943 (5.1264)	
Epoch: [3][800/836]	Batch Time 0.158 (0.228)	Data Time 0.000 (0.060)	Loss 4.6423 (5.1029)	
One epoch time elapsed: 189.80089116096497
Epoch: [4][0/836]	Batch Time 1.286 (1.286)	Data Time 1.048 (1.048)	Loss 4.9688 (4.9688)	
Epoch: [4][200/836]	Batch Time 0.183 (0.230)	Data Time 0.000 (0.062)	Loss 6.0652 (5.0017)	
Epoch: [4][400/836]	Batch Time 0.163 (0.228)	Data Time 0.000 (0.060)	Loss 5.0059 (4.9283)	
Epoch: [4][600/836]	Batch Time 0.145 (0.228)	Data Time 0.000 (0.060)	Loss 5.6577 (4.9144)	
Epoch: [4][800/836]	Batch Time 0.300 (0.226)	Data Time 0.100 (0.058)	Loss 5.0275 (4.8816)	
One epoch time elapsed: 188.36993026733398
Epoch: [5][0/836]	Batch Time 1.470 (1.470)	Data Time 1.246 (1.246)	Loss 4.8909 (4.8909)	
Epoch: [5][200/836]	Batch Time 0.171 (0.230)	Data Time 0.000 (0.059)	Loss 5.6043 (4.7666)	
Epoch: [5][400/836]	Batch Time 0.166 (0.227)	Data Time 0.000 (0.057)	Loss 4.9208 (4.7156)	
Epoch: [5][600/836]	Batch Time 0.195 (0.229)	Data Time 0.000 (0.060)	Loss 4.4705 (4.7000)	
Epoch: [5][800/836]	Batch Time 0.508 (0.227)	Data Time 0.342 (0.059)	Loss 4.3343 (4.6909)	
One epoch time elapsed: 189.58912801742554
Epoch: [6][0/836]	Batch Time 1.240 (1.240)	Data Time 1.005 (1.005)	Loss 4.8099 (4.8099)	
Epoch: [6][200/836]	Batch Time 0.167 (0.233)	Data Time 0.000 (0.061)	Loss 4.4876 (4.5493)	
Epoch: [6][400/836]	Batch Time 0.162 (0.231)	Data Time 0.000 (0.063)	Loss 5.8887 (4.5897)	
Epoch: [6][600/836]	Batch Time 0.179 (0.229)	Data Time 0.004 (0.061)	Loss 4.5737 (4.5625)	
Epoch: [6][800/836]	Batch Time 0.157 (0.228)	Data Time 0.000 (0.060)	Loss 3.8422 (4.5312)	
One epoch time elapsed: 190.1138195991516
Epoch: [7][0/836]	Batch Time 1.098 (1.098)	Data Time 0.873 (0.873)	Loss 4.9744 (4.9744)	
Epoch: [7][200/836]	Batch Time 0.162 (0.234)	Data Time 0.000 (0.062)	Loss 4.4858 (4.4309)	
Epoch: [7][400/836]	Batch Time 0.184 (0.230)	Data Time 0.005 (0.058)	Loss 4.4276 (4.4339)	
Epoch: [7][600/836]	Batch Time 0.161 (0.228)	Data Time 0.000 (0.057)	Loss 4.3583 (4.4180)	
Epoch: [7][800/836]	Batch Time 0.206 (0.225)	Data Time 0.002 (0.055)	Loss 3.7814 (4.3957)	
One epoch time elapsed: 187.18497467041016
Epoch: [8][0/836]	Batch Time 1.454 (1.454)	Data Time 1.215 (1.215)	Loss 3.1120 (3.1120)	
Epoch: [8][200/836]	Batch Time 0.219 (0.234)	Data Time 0.047 (0.065)	Loss 5.2783 (4.3430)	
Epoch: [8][400/836]	Batch Time 0.164 (0.230)	Data Time 0.005 (0.062)	Loss 4.0907 (4.3345)	
Epoch: [8][600/836]	Batch Time 0.176 (0.228)	Data Time 0.005 (0.060)	Loss 4.5139 (4.3260)	
Epoch: [8][800/836]	Batch Time 0.179 (0.227)	Data Time 0.000 (0.058)	Loss 4.0523 (4.3232)	
One epoch time elapsed: 188.83856654167175
Epoch: [9][0/836]	Batch Time 1.571 (1.571)	Data Time 1.342 (1.342)	Loss 4.0395 (4.0395)	
Epoch: [9][200/836]	Batch Time 0.181 (0.236)	Data Time 0.000 (0.064)	Loss 5.0176 (4.2491)	
Epoch: [9][400/836]	Batch Time 0.201 (0.230)	Data Time 0.000 (0.060)	Loss 4.2089 (4.2513)	
Epoch: [9][600/836]	Batch Time 0.531 (0.228)	Data Time 0.361 (0.058)	Loss 4.0101 (4.2519)	
Epoch: [9][800/836]	Batch Time 0.299 (0.227)	Data Time 0.131 (0.058)	Loss 4.9524 (4.2605)	
One epoch time elapsed: 188.8375539779663
Epoch: [10][0/836]	Batch Time 1.172 (1.172)	Data Time 0.971 (0.971)	Loss 4.8526 (4.8526)	
Epoch: [10][200/836]	Batch Time 0.166 (0.236)	Data Time 0.000 (0.065)	Loss 4.4555 (4.2157)	
Epoch: [10][400/836]	Batch Time 0.141 (0.231)	Data Time 0.000 (0.062)	Loss 3.8683 (4.1834)	
Epoch: [10][600/836]	Batch Time 0.180 (0.229)	Data Time 0.002 (0.060)	Loss 3.8690 (4.1805)	
Epoch: [10][800/836]	Batch Time 0.177 (0.228)	Data Time 0.000 (0.060)	Loss 4.0790 (4.1858)	
One epoch time elapsed: 189.74368691444397
DECAYING learning rate.
 The new LR is 0.000100

Epoch: [11][0/836]	Batch Time 0.983 (0.983)	Data Time 0.813 (0.813)	Loss 3.4874 (3.4874)	
Epoch: [11][200/836]	Batch Time 0.188 (0.224)	Data Time 0.000 (0.054)	Loss 3.6244 (3.9185)	
Epoch: [11][400/836]	Batch Time 0.162 (0.227)	Data Time 0.000 (0.057)	Loss 3.3646 (3.9036)	
Epoch: [11][600/836]	Batch Time 0.157 (0.225)	Data Time 0.000 (0.056)	Loss 3.6523 (3.8692)	
Epoch: [11][800/836]	Batch Time 0.180 (0.224)	Data Time 0.002 (0.055)	Loss 3.9211 (3.8585)	
One epoch time elapsed: 186.76427960395813
Epoch: [12][0/836]	Batch Time 1.169 (1.169)	Data Time 0.920 (0.920)	Loss 4.4329 (4.4329)	
Epoch: [12][200/836]	Batch Time 0.191 (0.229)	Data Time 0.004 (0.059)	Loss 3.8122 (3.8063)	
Epoch: [12][400/836]	Batch Time 0.369 (0.223)	Data Time 0.183 (0.054)	Loss 3.8494 (3.8130)	
Epoch: [12][600/836]	Batch Time 0.156 (0.224)	Data Time 0.000 (0.056)	Loss 4.5043 (3.8091)	
Epoch: [12][800/836]	Batch Time 0.189 (0.223)	Data Time 0.045 (0.055)	Loss 2.9455 (3.8067)	
One epoch time elapsed: 185.50233840942383
Epoch: [13][0/836]	Batch Time 1.682 (1.682)	Data Time 1.469 (1.469)	Loss 5.0712 (5.0712)	
Epoch: [13][200/836]	Batch Time 0.176 (0.230)	Data Time 0.000 (0.062)	Loss 3.1951 (3.7612)	
Epoch: [13][400/836]	Batch Time 0.484 (0.226)	Data Time 0.338 (0.058)	Loss 3.4912 (3.7832)	
Epoch: [13][600/836]	Batch Time 0.184 (0.225)	Data Time 0.005 (0.057)	Loss 3.5505 (3.7857)	
Epoch: [13][800/836]	Batch Time 0.185 (0.225)	Data Time 0.000 (0.057)	Loss 3.1499 (3.7784)	
One epoch time elapsed: 187.63824272155762
DECAYING learning rate.
 The new LR is 0.000010

Epoch: [14][0/836]	Batch Time 0.785 (0.785)	Data Time 0.620 (0.620)	Loss 3.3497 (3.3497)	
Epoch: [14][200/836]	Batch Time 0.439 (0.234)	Data Time 0.287 (0.063)	Loss 3.7739 (3.7425)	
Epoch: [14][400/836]	Batch Time 0.162 (0.227)	Data Time 0.000 (0.058)	Loss 3.0267 (3.7236)	
Epoch: [14][600/836]	Batch Time 0.542 (0.225)	Data Time 0.378 (0.056)	Loss 3.5497 (3.7200)	
Epoch: [14][800/836]	Batch Time 0.165 (0.224)	Data Time 0.000 (0.055)	Loss 3.3423 (3.7156)	
One epoch time elapsed: 186.4343798160553
Epoch: [15][0/836]	Batch Time 1.187 (1.187)	Data Time 0.947 (0.947)	Loss 4.2061 (4.2061)	
Epoch: [15][200/836]	Batch Time 0.169 (0.230)	Data Time 0.000 (0.057)	Loss 3.2545 (3.7227)	
Epoch: [15][400/836]	Batch Time 0.161 (0.229)	Data Time 0.000 (0.057)	Loss 3.9766 (3.7141)	
Epoch: [15][600/836]	Batch Time 0.633 (0.227)	Data Time 0.488 (0.057)	Loss 3.6556 (3.6803)	
Epoch: [15][800/836]	Batch Time 0.162 (0.226)	Data Time 0.000 (0.056)	Loss 3.8295 (3.6886)	
One epoch time elapsed: 188.71635007858276
Epoch: [16][0/836]	Batch Time 1.177 (1.177)	Data Time 0.957 (0.957)	Loss 3.6536 (3.6536)	
Epoch: [16][200/836]	Batch Time 0.175 (0.226)	Data Time 0.004 (0.059)	Loss 3.4490 (3.7114)	
Epoch: [16][400/836]	Batch Time 0.172 (0.225)	Data Time 0.000 (0.056)	Loss 3.2884 (3.7292)	
Epoch: [16][600/836]	Batch Time 0.188 (0.225)	Data Time 0.000 (0.056)	Loss 4.5743 (3.7307)	
Epoch: [16][800/836]	Batch Time 0.162 (0.226)	Data Time 0.000 (0.057)	Loss 3.6530 (3.7227)	
One epoch time elapsed: 188.5865752696991
time elapsed: 3214.2632751464844

Training SSD300 with VGG and using a PyTorch learning rate scheduler

This should be run after modifyng the training loop to use a learning rate scheduler.

In [20]:
start_time = time.time()
train_SSD(base_type='VGG', lr_type='pytorch_scheduler')
end_time = time.time()
print("time elapsed:", end_time - start_time)
Number of iterations 15000
Dataset length 5011
batch size 6
Number of Epochs to train: 17
Downloading: "https://download.pytorch.org/models/vgg16-397923af.pth" to /root/.cache/torch/hub/checkpoints/vgg16-397923af.pth

Loaded base model.

/usr/local/lib/python3.7/dist-packages/torch/nn/_reduction.py:44: UserWarning: size_average and reduce args will be deprecated, please use reduction='none' instead.
  warnings.warn(warning.format(ret))
Epoch: [0][0/836]	Batch Time 4.654 (4.654)	Data Time 1.728 (1.728)	Loss 22.6671 (22.6671)	
Epoch: [0][200/836]	Batch Time 0.264 (0.408)	Data Time 0.000 (0.138)	Loss 6.1692 (10.4057)	
Epoch: [0][400/836]	Batch Time 0.262 (0.401)	Data Time 0.000 (0.137)	Loss 6.0956 (8.3992)	
Epoch: [0][600/836]	Batch Time 0.252 (0.396)	Data Time 0.000 (0.134)	Loss 6.3804 (7.6454)	
Epoch: [0][800/836]	Batch Time 0.340 (0.401)	Data Time 0.091 (0.140)	Loss 6.1311 (7.2588)	
One epoch time elapsed: 337.76591324806213
Epoch: [1][0/836]	Batch Time 1.497 (1.497)	Data Time 1.112 (1.112)	Loss 6.4130 (6.4130)	
Epoch: [1][200/836]	Batch Time 0.272 (0.283)	Data Time 0.000 (0.006)	Loss 6.3153 (5.8622)	
Epoch: [1][400/836]	Batch Time 0.279 (0.278)	Data Time 0.000 (0.003)	Loss 6.6768 (5.8256)	
Epoch: [1][600/836]	Batch Time 0.265 (0.276)	Data Time 0.000 (0.002)	Loss 6.2358 (5.7851)	
Epoch: [1][800/836]	Batch Time 0.258 (0.275)	Data Time 0.000 (0.002)	Loss 5.6275 (5.7131)	
One epoch time elapsed: 229.61985611915588
Epoch: [2][0/836]	Batch Time 1.045 (1.045)	Data Time 0.697 (0.697)	Loss 5.7291 (5.7291)	
Epoch: [2][200/836]	Batch Time 0.271 (0.283)	Data Time 0.000 (0.008)	Loss 5.1248 (5.3921)	
Epoch: [2][400/836]	Batch Time 0.256 (0.278)	Data Time 0.000 (0.004)	Loss 5.2434 (5.3524)	
Epoch: [2][600/836]	Batch Time 0.293 (0.277)	Data Time 0.005 (0.003)	Loss 5.0973 (5.2891)	
Epoch: [2][800/836]	Batch Time 0.262 (0.275)	Data Time 0.000 (0.002)	Loss 5.6273 (5.2527)	
One epoch time elapsed: 229.88495135307312
Epoch: [3][0/836]	Batch Time 1.144 (1.144)	Data Time 0.804 (0.804)	Loss 5.3864 (5.3864)	
Epoch: [3][200/836]	Batch Time 0.262 (0.282)	Data Time 0.000 (0.006)	Loss 4.8018 (4.9325)	
Epoch: [3][400/836]	Batch Time 0.290 (0.277)	Data Time 0.000 (0.003)	Loss 4.8249 (4.9218)	
Epoch: [3][600/836]	Batch Time 0.293 (0.277)	Data Time 0.000 (0.003)	Loss 5.0203 (4.9115)	
Epoch: [3][800/836]	Batch Time 0.269 (0.276)	Data Time 0.000 (0.002)	Loss 4.7089 (4.8770)	
One epoch time elapsed: 230.2415018081665
Epoch: [4][0/836]	Batch Time 1.130 (1.130)	Data Time 0.787 (0.787)	Loss 4.3891 (4.3891)	
Epoch: [4][200/836]	Batch Time 0.269 (0.278)	Data Time 0.000 (0.006)	Loss 3.9110 (4.6806)	
Epoch: [4][400/836]	Batch Time 0.290 (0.275)	Data Time 0.010 (0.003)	Loss 4.4941 (4.6121)	
Epoch: [4][600/836]	Batch Time 0.285 (0.275)	Data Time 0.000 (0.002)	Loss 4.7234 (4.5665)	
Epoch: [4][800/836]	Batch Time 0.274 (0.274)	Data Time 0.000 (0.002)	Loss 4.3148 (4.5826)	
One epoch time elapsed: 228.72575569152832
Epoch: [5][0/836]	Batch Time 1.407 (1.407)	Data Time 1.050 (1.050)	Loss 5.2769 (5.2769)	
Epoch: [5][200/836]	Batch Time 0.272 (0.283)	Data Time 0.000 (0.007)	Loss 4.8218 (4.4614)	
Epoch: [5][400/836]	Batch Time 0.269 (0.278)	Data Time 0.000 (0.004)	Loss 4.5552 (4.4090)	
Epoch: [5][600/836]	Batch Time 0.256 (0.276)	Data Time 0.000 (0.003)	Loss 4.6770 (4.3983)	
Epoch: [5][800/836]	Batch Time 0.262 (0.275)	Data Time 0.000 (0.002)	Loss 4.3251 (4.3755)	
One epoch time elapsed: 229.44282507896423
Epoch: [6][0/836]	Batch Time 1.310 (1.310)	Data Time 0.958 (0.958)	Loss 3.9959 (3.9959)	
Epoch: [6][200/836]	Batch Time 0.300 (0.281)	Data Time 0.000 (0.008)	Loss 4.0475 (4.2912)	
Epoch: [6][400/836]	Batch Time 0.269 (0.276)	Data Time 0.000 (0.004)	Loss 3.7803 (4.2286)	
Epoch: [6][600/836]	Batch Time 0.265 (0.275)	Data Time 0.000 (0.003)	Loss 3.8826 (4.1866)	
Epoch: [6][800/836]	Batch Time 0.258 (0.275)	Data Time 0.000 (0.002)	Loss 4.4138 (4.1670)	
One epoch time elapsed: 229.3677020072937
Epoch: [7][0/836]	Batch Time 1.674 (1.674)	Data Time 1.302 (1.302)	Loss 4.4448 (4.4448)	
Epoch: [7][200/836]	Batch Time 0.254 (0.282)	Data Time 0.000 (0.007)	Loss 3.7775 (4.0576)	
Epoch: [7][400/836]	Batch Time 0.263 (0.277)	Data Time 0.000 (0.004)	Loss 3.7607 (4.0619)	
Epoch: [7][600/836]	Batch Time 0.268 (0.275)	Data Time 0.000 (0.003)	Loss 3.3281 (4.0370)	
Epoch: [7][800/836]	Batch Time 0.257 (0.274)	Data Time 0.000 (0.002)	Loss 4.4868 (4.0464)	
One epoch time elapsed: 229.09616875648499
Epoch: [8][0/836]	Batch Time 1.467 (1.467)	Data Time 1.090 (1.090)	Loss 3.5455 (3.5455)	
Epoch: [8][200/836]	Batch Time 0.268 (0.284)	Data Time 0.000 (0.007)	Loss 3.4644 (3.9842)	
Epoch: [8][400/836]	Batch Time 0.268 (0.279)	Data Time 0.000 (0.004)	Loss 3.6833 (3.9762)	
Epoch: [8][600/836]	Batch Time 0.283 (0.277)	Data Time 0.010 (0.003)	Loss 3.6010 (3.9671)	
Epoch: [8][800/836]	Batch Time 0.283 (0.277)	Data Time 0.000 (0.002)	Loss 4.1136 (3.9501)	
One epoch time elapsed: 230.722074508667
Epoch: [9][0/836]	Batch Time 1.427 (1.427)	Data Time 1.064 (1.064)	Loss 3.5591 (3.5591)	
Epoch: [9][200/836]	Batch Time 0.262 (0.283)	Data Time 0.000 (0.006)	Loss 3.4101 (3.8174)	
Epoch: [9][400/836]	Batch Time 0.286 (0.279)	Data Time 0.000 (0.003)	Loss 3.0321 (3.8210)	
Epoch: [9][600/836]	Batch Time 0.288 (0.278)	Data Time 0.000 (0.002)	Loss 3.8851 (3.8466)	
Epoch: [9][800/836]	Batch Time 0.268 (0.277)	Data Time 0.005 (0.002)	Loss 4.2924 (3.8321)	
One epoch time elapsed: 230.84747195243835
Epoch: [10][0/836]	Batch Time 1.849 (1.849)	Data Time 1.499 (1.499)	Loss 3.4529 (3.4529)	
Epoch: [10][200/836]	Batch Time 0.275 (0.281)	Data Time 0.000 (0.008)	Loss 3.8834 (3.8943)	
Epoch: [10][400/836]	Batch Time 0.259 (0.277)	Data Time 0.000 (0.004)	Loss 4.1780 (3.8691)	
Epoch: [10][600/836]	Batch Time 0.272 (0.275)	Data Time 0.000 (0.003)	Loss 3.6208 (3.8297)	
Epoch: [10][800/836]	Batch Time 0.274 (0.275)	Data Time 0.000 (0.002)	Loss 4.4512 (3.8072)	
One epoch time elapsed: 229.34588027000427
Epoch: [11][0/836]	Batch Time 1.213 (1.213)	Data Time 0.869 (0.869)	Loss 3.7761 (3.7761)	
Epoch: [11][200/836]	Batch Time 0.272 (0.281)	Data Time 0.000 (0.006)	Loss 4.3654 (3.7735)	
Epoch: [11][400/836]	Batch Time 0.283 (0.276)	Data Time 0.005 (0.003)	Loss 3.8563 (3.7452)	
Epoch: [11][600/836]	Batch Time 0.279 (0.275)	Data Time 0.000 (0.002)	Loss 3.9405 (3.7186)	
Epoch: [11][800/836]	Batch Time 0.282 (0.274)	Data Time 0.000 (0.002)	Loss 3.7918 (3.7278)	
One epoch time elapsed: 228.5365605354309
Epoch: [12][0/836]	Batch Time 1.623 (1.623)	Data Time 1.280 (1.280)	Loss 2.9611 (2.9611)	
Epoch: [12][200/836]	Batch Time 0.276 (0.282)	Data Time 0.000 (0.007)	Loss 4.3129 (3.5964)	
Epoch: [12][400/836]	Batch Time 0.266 (0.278)	Data Time 0.000 (0.004)	Loss 4.1958 (3.6317)	
Epoch: [12][600/836]	Batch Time 0.281 (0.276)	Data Time 0.000 (0.003)	Loss 3.8616 (3.6281)	
Epoch: [12][800/836]	Batch Time 0.281 (0.275)	Data Time 0.000 (0.002)	Loss 2.9924 (3.6234)	
One epoch time elapsed: 229.4750211238861
Epoch: [13][0/836]	Batch Time 1.371 (1.371)	Data Time 1.027 (1.027)	Loss 4.2271 (4.2271)	
Epoch: [13][200/836]	Batch Time 0.259 (0.278)	Data Time 0.000 (0.006)	Loss 3.9140 (3.5604)	
Epoch: [13][400/836]	Batch Time 0.286 (0.275)	Data Time 0.000 (0.003)	Loss 3.8388 (3.6115)	
Epoch: [13][600/836]	Batch Time 0.274 (0.274)	Data Time 0.000 (0.002)	Loss 3.0518 (3.6078)	
Epoch: [13][800/836]	Batch Time 0.276 (0.274)	Data Time 0.000 (0.002)	Loss 4.1664 (3.5797)	
One epoch time elapsed: 228.58099961280823
Epoch: [14][0/836]	Batch Time 1.014 (1.014)	Data Time 0.710 (0.710)	Loss 3.7360 (3.7360)	
Epoch: [14][200/836]	Batch Time 0.257 (0.277)	Data Time 0.000 (0.006)	Loss 3.6842 (3.5780)	
Epoch: [14][400/836]	Batch Time 0.260 (0.274)	Data Time 0.000 (0.003)	Loss 3.4614 (3.5667)	
Epoch: [14][600/836]	Batch Time 0.268 (0.273)	Data Time 0.000 (0.002)	Loss 3.6351 (3.5374)	
Epoch: [14][800/836]	Batch Time 0.278 (0.273)	Data Time 0.000 (0.002)	Loss 3.4142 (3.5386)	
One epoch time elapsed: 228.3314790725708
Epoch: [15][0/836]	Batch Time 1.412 (1.412)	Data Time 1.053 (1.053)	Loss 3.5658 (3.5658)	
Epoch: [15][200/836]	Batch Time 0.256 (0.281)	Data Time 0.000 (0.007)	Loss 4.1762 (3.5602)	
Epoch: [15][400/836]	Batch Time 0.275 (0.277)	Data Time 0.000 (0.004)	Loss 2.6192 (3.5109)	
Epoch: [15][600/836]	Batch Time 0.276 (0.275)	Data Time 0.000 (0.003)	Loss 4.2134 (3.5037)	
Epoch: [15][800/836]	Batch Time 0.261 (0.274)	Data Time 0.000 (0.002)	Loss 3.7060 (3.4974)	
One epoch time elapsed: 228.71640372276306
Epoch: [16][0/836]	Batch Time 1.996 (1.996)	Data Time 1.671 (1.671)	Loss 4.9494 (4.9494)	
Epoch: [16][200/836]	Batch Time 0.262 (0.282)	Data Time 0.000 (0.009)	Loss 3.7111 (3.5139)	
Epoch: [16][400/836]	Batch Time 0.267 (0.279)	Data Time 0.000 (0.005)	Loss 3.9174 (3.4937)	
Epoch: [16][600/836]	Batch Time 0.277 (0.277)	Data Time 0.000 (0.003)	Loss 3.1979 (3.4784)	
Epoch: [16][800/836]	Batch Time 0.280 (0.276)	Data Time 0.000 (0.003)	Loss 3.7804 (3.4631)	
One epoch time elapsed: 230.2158007621765
time elapsed: 4029.6473059654236

Testing

Now let's run the eval code, it should take about 30 minutes per model.

In [21]:
from utils import *
# from datasets import PascalVOCDataset
from tqdm import tqdm
from pprint import PrettyPrinter

# Good formatting when printing the APs for each class and mAP
pp = PrettyPrinter()

# Parameters
data_folder = './'
keep_difficult = True  # difficult ground truth objects must always be considered in mAP calculation, because these objects DO exist!
batch_size = 64
workers = 4
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
checkpoint = './checkpoint_ssd300_VGG.pth.tar'

# Load model checkpoint that is to be evaluated
checkpoint = torch.load(checkpoint)
model = checkpoint['model']
model = model.to(device)

# Switch to eval mode
model.eval()

# Load test data
test_dataset = PascalVOCDataset(data_folder,
                                split='test',
                                keep_difficult=keep_difficult)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=False,
                                          collate_fn=test_dataset.collate_fn, num_workers=workers, pin_memory=True)


def evaluate(test_loader, model):
    """
    Evaluate.

    :param test_loader: DataLoader for test data
    :param model: model
    """

    # Make sure it's in eval mode
    model.eval()

    # Lists to store detected and true boxes, labels, scores
    det_boxes = list()
    det_labels = list()
    det_scores = list()
    true_boxes = list()
    true_labels = list()
    true_difficulties = list()  # it is necessary to know which objects are 'difficult', see 'calculate_mAP' in utils.py

    with torch.no_grad():
        # Batches
        for i, (images, boxes, labels, difficulties) in enumerate(tqdm(test_loader, desc='Evaluating')):
            images = images.to(device)  # (N, 3, 300, 300)

            # Forward prop.
            predicted_locs, predicted_scores = model(images)

            # Detect objects in SSD output
            det_boxes_batch, det_labels_batch, det_scores_batch = model.detect_objects(predicted_locs, predicted_scores,
                                                                                       min_score=0.01, max_overlap=0.45,
                                                                                       top_k=200)
            # Evaluation MUST be at min_score=0.01, max_overlap=0.45, top_k=200 for fair comparision with the paper's results and other repos

            # Store this batch's results for mAP calculation
            boxes = [b.to(device) for b in boxes]
            labels = [l.to(device) for l in labels]
            difficulties = [d.to(device) for d in difficulties]

            det_boxes.extend(det_boxes_batch)
            det_labels.extend(det_labels_batch)
            det_scores.extend(det_scores_batch)
            true_boxes.extend(boxes)
            true_labels.extend(labels)
            true_difficulties.extend(difficulties)

        # Calculate mAP
        APs, mAP = calculate_mAP(det_boxes, det_labels, det_scores, true_boxes, true_labels, true_difficulties)

    # Print AP for each class
    pp.pprint(APs)

    print('\nMean Average Precision (mAP): %.3f' % mAP)

Testing SSD300 with VGG and the original learning rate adjuster

Your model should output an mAP about the same as this:

Mean Average Precision (mAP): 0.589

In [23]:
checkpoint = './checkpoint_ssd300_VGG.pth.tar'

# Load model checkpoint that is to be evaluated
checkpoint = torch.load(checkpoint)
model = checkpoint['model']
model = model.to(device)

# Switch to eval mode
model.eval()

# Load test data
test_dataset = PascalVOCDataset(data_folder,
                                split='test',
                                keep_difficult=keep_difficult)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=False,
                                          collate_fn=test_dataset.collate_fn, num_workers=workers, pin_memory=True)

evaluate(test_loader, model)
Evaluating:   0%|          | 0/78 [00:00<?, ?it/s]/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:183: UserWarning: indexing with dtype torch.uint8 is now deprecated, please use a dtype torch.bool instead. (Triggered internally at  /pytorch/aten/src/ATen/native/IndexingUtils.h:25.)
/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:185: UserWarning: indexing with dtype torch.uint8 is now deprecated, please use a dtype torch.bool instead. (Triggered internally at  /pytorch/aten/src/ATen/native/IndexingUtils.h:25.)
Evaluating: 100%|██████████| 78/78 [16:42<00:00, 12.85s/it]
{'aeroplane': 0.6626229286193848,
 'bicycle': 0.7145682573318481,
 'bird': 0.5881743431091309,
 'boat': 0.4219280183315277,
 'bottle': 0.1777588278055191,
 'bus': 0.6779816746711731,
 'car': 0.7545259594917297,
 'cat': 0.7797669768333435,
 'chair': 0.3029060363769531,
 'cow': 0.6161858439445496,
 'diningtable': 0.470374196767807,
 'dog': 0.7425361275672913,
 'horse': 0.7593265175819397,
 'motorbike': 0.7122815251350403,
 'person': 0.6417626738548279,
 'pottedplant': 0.24432134628295898,
 'sheep': 0.6137462854385376,
 'sofa': 0.5753262639045715,
 'train': 0.7309077382087708,
 'tvmonitor': 0.6230891942977905}

Mean Average Precision (mAP): 0.591

Testing SSD300 with ResNet and the original learning rate adjuster

In [24]:
checkpoint = './checkpoint_ssd300_ResNet.pth.tar'

# Load model checkpoint that is to be evaluated
checkpoint = torch.load(checkpoint)
model = checkpoint['model']
model = model.to(device)

# Switch to eval mode
model.eval()

# Load test data
test_dataset = PascalVOCDataset(data_folder,
                                split='test',
                                keep_difficult=keep_difficult)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=False,
                                          collate_fn=test_dataset.collate_fn, num_workers=workers, pin_memory=True)

evaluate(test_loader, model)
Evaluating:   0%|          | 0/78 [00:00<?, ?it/s]/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:183: UserWarning: indexing with dtype torch.uint8 is now deprecated, please use a dtype torch.bool instead. (Triggered internally at  /pytorch/aten/src/ATen/native/IndexingUtils.h:25.)
/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:185: UserWarning: indexing with dtype torch.uint8 is now deprecated, please use a dtype torch.bool instead. (Triggered internally at  /pytorch/aten/src/ATen/native/IndexingUtils.h:25.)
Evaluating: 100%|██████████| 78/78 [31:16<00:00, 24.06s/it]
{'aeroplane': 0.5284181833267212,
 'bicycle': 0.558178722858429,
 'bird': 0.512355625629425,
 'boat': 0.21529321372509003,
 'bottle': 0.21342934668064117,
 'bus': 0.553388774394989,
 'car': 0.726449728012085,
 'cat': 0.6419401168823242,
 'chair': 0.3233609199523926,
 'cow': 0.4418167769908905,
 'diningtable': 0.4005905091762543,
 'dog': 0.5928902626037598,
 'horse': 0.6941666603088379,
 'motorbike': 0.6347066164016724,
 'person': 0.6290072798728943,
 'pottedplant': 0.22725772857666016,
 'sheep': 0.3689113259315491,
 'sofa': 0.5610581636428833,
 'train': 0.5594823956489563,
 'tvmonitor': 0.5455713272094727}

Mean Average Precision (mAP): 0.496

Training SSD300 with VGG and using a PyTorch learning rate scheduler

In [22]:
checkpoint = './checkpoint_ssd300_VGG_scheduler.pth.tar'

# Load mod=el checkpoint that is to be evaluated
checkpoint = torch.load(checkpoint)
model = checkpoint['model']
model = model.to(device)

# Switch to eval mode
model.eval()

# Load test data
test_dataset = PascalVOCDataset(data_folder,
                                split='test',
                                keep_difficult=keep_difficult)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=False,
                                          collate_fn=test_dataset.collate_fn, num_workers=workers, pin_memory=True)

evaluate(test_loader, model)
Evaluating:   0%|          | 0/78 [00:00<?, ?it/s]/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:183: UserWarning: indexing with dtype torch.uint8 is now deprecated, please use a dtype torch.bool instead. (Triggered internally at  /pytorch/aten/src/ATen/native/IndexingUtils.h:25.)
/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:185: UserWarning: indexing with dtype torch.uint8 is now deprecated, please use a dtype torch.bool instead. (Triggered internally at  /pytorch/aten/src/ATen/native/IndexingUtils.h:25.)
Evaluating: 100%|██████████| 78/78 [16:57<00:00, 13.04s/it]
{'aeroplane': 0.5895159840583801,
 'bicycle': 0.7022255063056946,
 'bird': 0.58998042345047,
 'boat': 0.37313371896743774,
 'bottle': 0.19802646338939667,
 'bus': 0.7056620121002197,
 'car': 0.7490395903587341,
 'cat': 0.7298564910888672,
 'chair': 0.30513131618499756,
 'cow': 0.6335718035697937,
 'diningtable': 0.45657870173454285,
 'dog': 0.714390754699707,
 'horse': 0.7339320182800293,
 'motorbike': 0.6738119125366211,
 'person': 0.6149888038635254,
 'pottedplant': 0.1659858226776123,
 'sheep': 0.4867994785308838,
 'sofa': 0.561204731464386,
 'train': 0.60589998960495,
 'tvmonitor': 0.5350574254989624}

Mean Average Precision (mAP): 0.556

Viewing results

And lastly let's view some images with our detections!

In [23]:
from torchvision import transforms
from utils import *
from PIL import Image, ImageDraw, ImageFont
import matplotlib.pyplot as plt

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# Load model checkpoint
checkpoint = 'checkpoint_ssd300_VGG_scheduler.pth.tar'
checkpoint = torch.load(checkpoint)
start_epoch = checkpoint['epoch'] + 1
print('\nLoaded checkpoint from epoch %d.\n' % start_epoch)
model = checkpoint['model']
model = model.to(device)
model.eval()

# Transforms
resize = transforms.Resize((300, 300))
to_tensor = transforms.ToTensor()
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                 std=[0.229, 0.224, 0.225])


def detect(original_image, min_score, max_overlap, top_k, suppress=None):
    """
    Detect objects in an image with a trained SSD300, and visualize the results.

    :param original_image: image, a PIL Image
    :param min_score: minimum threshold for a detected box to be considered a match for a certain class
    :param max_overlap: maximum overlap two boxes can have so that the one with the lower score is not suppressed via Non-Maximum Suppression (NMS)
    :param top_k: if there are a lot of resulting detection across all classes, keep only the top 'k'
    :param suppress: classes that you know for sure cannot be in the image or you do not want in the image, a list
    :return: annotated image, a PIL Image
    """

    # Transform
    image = normalize(to_tensor(resize(original_image)))

    # Move to default device
    image = image.to(device)

    # Forward prop.
    predicted_locs, predicted_scores = model(image.unsqueeze(0))

    # Detect objects in SSD output
    det_boxes, det_labels, det_scores = model.detect_objects(predicted_locs, predicted_scores, min_score=min_score,
                                                             max_overlap=max_overlap, top_k=top_k)

    # Move detections to the CPU
    det_boxes = det_boxes[0].to('cpu')

    # Transform to original image dimensions
    original_dims = torch.FloatTensor(
        [original_image.width, original_image.height, original_image.width, original_image.height]).unsqueeze(0)
    det_boxes = det_boxes * original_dims

    # Decode class integer labels
    det_labels = [rev_label_map[l] for l in det_labels[0].to('cpu').tolist()]

    # If no objects found, the detected labels will be set to ['0.'], i.e. ['background'] in SSD300.detect_objects() in model.py
    if det_labels == ['background']:
        # Just return original image
        return original_image

    # Annotate
    annotated_image = original_image
    draw = ImageDraw.Draw(annotated_image)
    font = ImageFont.load_default() # ImageFont.truetype("./calibril.ttf", 15)

    # Suppress specific classes, if needed
    for i in range(det_boxes.size(0)):
        if suppress is not None:
            if det_labels[i] in suppress:
                continue

        # Boxes
        box_location = det_boxes[i].tolist()
        draw.rectangle(xy=box_location, outline=label_color_map[det_labels[i]])
        draw.rectangle(xy=[l + 1. for l in box_location], outline=label_color_map[
            det_labels[i]])  # a second rectangle at an offset of 1 pixel to increase line thickness
        # draw.rectangle(xy=[l + 2. for l in box_location], outline=label_color_map[
        #     det_labels[i]])  # a third rectangle at an offset of 1 pixel to increase line thickness
        # draw.rectangle(xy=[l + 3. for l in box_location], outline=label_color_map[
        #     det_labels[i]])  # a fourth rectangle at an offset of 1 pixel to increase line thickness

        # Text
        text_size = font.getsize(det_labels[i].upper())
        text_location = [box_location[0] + 2., box_location[1] - text_size[1]]
        textbox_location = [box_location[0], box_location[1] - text_size[1], box_location[0] + text_size[0] + 4.,
                            box_location[1]]
        draw.rectangle(xy=textbox_location, fill=label_color_map[det_labels[i]])
        draw.text(xy=text_location, text=det_labels[i].upper(), fill='white',
                  font=font)
    del draw

    return annotated_image

relevant_images = [
  '000012.jpg', # Car
  '000014.jpg', # Car, Bus
  '000026.jpg', # Car
  '000038.jpg', # Cyclist
  '000054.jpg', # Bus
  '000091.jpg', # Vehicles parked, far from camera
  '000111.jpg', # Cyclists in race, far from camera
  '000129.jpg' # Cyclists in race, close to camera
]

for rel_img_file_name in relevant_images:
    img_path = '/content/gdrive/MyDrive/Colab Notebooks/ece495_assignment4/VOCdevkit/VOC2007/JPEGImages/' + rel_img_file_name
    original_image = Image.open(img_path, mode='r')
    original_image = original_image.convert('RGB')
    img = detect(original_image, min_score=0.2, max_overlap=0.5, top_k=200)

    fig = plt.figure(figsize=(10,10))
    ax1 = fig.add_subplot(1,1,1)
    ax1.imshow(img)
Loaded checkpoint from epoch 17.

/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:183: UserWarning: indexing with dtype torch.uint8 is now deprecated, please use a dtype torch.bool instead. (Triggered internally at  /pytorch/aten/src/ATen/native/IndexingUtils.h:25.)
/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:185: UserWarning: indexing with dtype torch.uint8 is now deprecated, please use a dtype torch.bool instead. (Triggered internally at  /pytorch/aten/src/ATen/native/IndexingUtils.h:25.)
In [ ]: